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的不同值来判断走不同的分支。
3.3.运行程序结果为:Hello Cary。
作者:生鱼片
本文版权归作者和博客园共有,欢迎转载,但未经作者同意必须保留此段声明,且在文章页面明显位置给出原文连接,否则保留追究法律责任的权利。
分类:
WF
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 单线程的Redis速度为什么快?
· 展开说说关于C#中ORM框架的用法!
· SQL Server 2025 AI相关能力初探
· Pantheons:用 TypeScript 打造主流大模型对话的一站式集成库