博客园  :: 首页  :: 联系 :: 订阅 订阅  :: 管理

WF4.0 Beta2:Switch<T>活动中使用复杂类型

Posted on 2009-10-27 21:34  生鱼片  阅读(1999)  评论(9编辑  收藏  举报

Switch<T>是WF4.0中新增的活动。功能类似于C#语言中的Switch语句,但是C#的Switch语句只能是一般的Int,String等类型。在WF4.0中Switch<T>可以使用
用于自定义的复杂类型。下面例子完成根据不同的Person执行不同的分支。

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,可以说是任何类型)转换到另一种类型(一般为string),或者将另一种类型转换回来。
我们实现上面的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.工作流设计如下:

3.1.定义一个Person类型的变量p1,Scope为Sequence。

3.2.工作流设计中首先是一个Assign活动来实例化p1,然后在Switc<Person>中根据p1的不同值来判断走不同的分支。

image

3.3.运行程序结果为:Hello Cary。