可能重复:
C# - "开启类型"有比这更好的选择吗?
C#不支持切换对象的类型.模拟这个的最佳模式是什么:
switch (typeof(MyObj))
case Type1:
case Type2:
case Type3:
Run Code Online (Sandbox Code Playgroud)
谢谢!
Mar*_*k H 181
我通常使用类型和代表的字典.
var @switch = new Dictionary<Type, Action> {
{ typeof(Type1), () => ... },
{ typeof(Type2), () => ... },
{ typeof(Type3), () => ... },
};
@switch[typeof(MyType)]();
Run Code Online (Sandbox Code Playgroud)
它不太灵活,因为你无法通过案件,继续等等.但我很少这样做.
gjv*_*amp 59
这是C#游戏中的漏洞,还没有银弹.
你应该谷歌'访客模式',但它可能有点沉重,但你仍然应该知道的事情.
以下是使用Linq的另一个问题:http://community.bartdesmet.net/blogs/bart/archive/2008/03/30/a-functional-c-type-switch.aspx
否则沿着这些方向的东西会有所帮助
switch (MyObj)
case Type1 t1:
case Type2 t2:
case Type3 t3:
Run Code Online (Sandbox Code Playgroud)
等等
cdi*_*ins 25
在类型为c#的Switch case中有一个简单的答案,它使用类型字典来查找lambda函数.
以下是它的使用方法
var ts = new TypeSwitch()
.Case((int x) => Console.WriteLine("int"))
.Case((bool x) => Console.WriteLine("bool"))
.Case((string x) => Console.WriteLine("string"));
ts.Switch(42);
ts.Switch(false);
ts.Switch("hello");
Run Code Online (Sandbox Code Playgroud)
在开关/模式匹配思想的模式匹配(类型和运行时检查条件)方面,还有一个通用的解决方案.
var getRentPrice = new PatternMatcher<int>()
.Case<MotorCycle>(bike => 100 + bike.Cylinders * 10)
.Case<Bicycle>(30)
.Case<Car>(car => car.EngineType == EngineType.Diesel, car => 220 + car.Doors * 20)
.Case<Car>(car => car.EngineType == EngineType.Gasoline, car => 200 + car.Doors * 20)
.Default(0);
var vehicles = new object[] {
new Car { EngineType = EngineType.Diesel, Doors = 2 },
new Car { EngineType = EngineType.Diesel, Doors = 4 },
new Car { EngineType = EngineType.Gasoline, Doors = 3 },
new Car { EngineType = EngineType.Gasoline, Doors = 5 },
new Bicycle(),
new MotorCycle { Cylinders = 2 },
new MotorCycle { Cylinders = 3 },
};
foreach (var v in vehicles)
{
Console.WriteLine("Vehicle of type {0} costs {1} to rent", v.GetType(), getRentPrice.Match(v));
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
166586 次 |
| 最近记录: |