詳解WF4.0 Beta2中的Switch<T>活動
對于微軟的WF工作流,很多開發(fā)人員都有過接觸。對于新版的WF4.0 Beta2,有許多新特性值得我們?nèi)ラ_發(fā)和體驗(yàn)。這些新特性能給我們帶來事半功倍的效果。
Switch<T>是WF4.0中新增的活動。功能類似于C#語言中的Switch語句,但是C#的Switch語句只能是一般的Int,String等類型。在WF4.0中Switch<T>可以使用
用于自定義的復(fù)雜類型。下面例子完成根據(jù)不同的Person執(zhí)行不同的分支。
1.下面是Person類,在Person類中我們必須要重寫Equals方法和GetHashCode方法,代碼如下:
- [TypeConverter(typeof(PersonConverter))]
- public class Person
- {
- public string Name { get; set; }
- public int Age { get; set; }
- public Person()
- {
- this.Age = 15;
- }
- public Person(string name, int age)
- {
- this.Name = name;
- this.Age = age;
- }
- public Person(string name) : this()
- {
- this.Name = name;
- }
- public override bool Equals(object obj)
- {
- Person person = obj as Person;
- if (person != null)
- {
- return string.Equals(this.Name, person.Name);
- }
- return false;
- }
- public override int GetHashCode()
- {
- if (this.Name != null)
- {
- return this.Name.GetHashCode();
- }
- return 0;
- }
- }
2.TypeConverter 類是.NET提供的類型換器 就是將一種類型(object,可以說是任何類型)轉(zhuǎn)換到另一種類型(一般為string),或者將另一種類型轉(zhuǎn)換回來。
我們實(shí)現(xiàn)上面的Person的PersonConverter,如下:
- public class PersonConverter : TypeConverter
- {
- public override bool CanConvertFrom(ITypeDescriptorContext context,Type sourceType)
- {
- return (sourceType == typeof(string));
- }
- public override object ConvertFrom(ITypeDescriptorContext context,CultureInfo culture, object value)
- {
- if (value == null)
- {
- return null;
- }
- if (value is string)
- {
- return new Person
- {
- Name = (string)value
- };
- }
- return base.ConvertFrom(context, culture, value);
- }
- public override object ConvertTo(ITypeDescriptorContext context,CultureInfo culture, object value, Type destinationType)
- {
- if (destinationType == typeof(string))
- {
- if (value != null)
- {
- return ((Person)value).Name;
- }
- else
- {
- return null;
- }
- }
- return base.ConvertTo(context, culture, value, destinationType);
- }
- }
3.工作流設(shè)計(jì)如下:
3.1.定義一個Person類型的變量p1,Scope為Sequence。
3.2.工作流設(shè)計(jì)中首先是一個Assign活動來實(shí)例化p1,然后在Switc<Person>中根據(jù)p1的不同值來判斷走不同的分支。
3.3.運(yùn)行程序結(jié)果為:Hello Cary。
原文標(biāo)題:WF4.0 Beta2:Switch
鏈接:http://www.cnblogs.com/carysun/archive/2009/10/27/wf4-beta2-switch.html
【編輯推薦】