Using Case/Switch and GetType to determine the object
Possible Duplicate:
C# - Is there a better alternative than this to 'switch on type'?
If you want to switch
on a type of object, what is the best way to do this?
Code snippet
private int GetNodeType(NodeDTO node)
{
switch (node.GetType())
{
case typeof(CasusNodeDTO):
return 1;
case typeof(BucketNodeDTO):
return 3;
case typeof(BranchNodeDTO):
return 0;
case typeof(LeafNodeDTO):
return 2;
default:
return -1;
}
}
I know this doesn't work that way, but I was wondering how you could solve this. Is an if/else
statement appropriate in this case?
Or do you use the switch and add .ToString()
to the type?
If I really had to switch
on type of object, I'd use .ToString()
. However, I would avoid it at all costs: IDictionary<Type, int>
will do much better, visitor might be an overkill but otherwise it is still a perfectly fine solution.
这不会直接解决您的问题,因为您希望切换自己的用户定义类型,但为了其他只想打开内置类型的用户的利益,可以使用TypeCode枚举:
switch (Type.GetTypeCode(node.GetType()))
{
case TypeCode.Decimal:
// Handle Decimal
break;
case TypeCode.Int32:
// Handle Int32
break;
...
}
In the MSDN blog post Many Questions: switch on type is some information on why .NET does not provide switching on types.
As usual - workarounds always exists.
This one isn't mine, but unfortunately I have lost the source. It makes switching on types possible, but I personally think it's quite awkward (the dictionary idea is better):
public class Switch
{
public Switch(Object o)
{
Object = o;
}
public Object Object { get; private set; }
}
/// <summary>
/// Extensions, because otherwise casing fails on Switch==null
/// </summary>
public static class SwitchExtensions
{
public static Switch Case<T>(this Switch s, Action<T> a)
where T : class
{
return Case(s, o => true, a, false);
}
public static Switch Case<T>(this Switch s, Action<T> a,
bool fallThrough) where T : class
{
return Case(s, o => true, a, fallThrough);
}
public static Switch Case<T>(this Switch s,
Func<T, bool> c, Action<T> a) where T : class
{
return Case(s, c, a, false);
}
public static Switch Case<T>(this Switch s,
Func<T, bool> c, Action<T> a, bool fallThrough) where T : class
{
if (s == null)
{
return null;
}
T t = s.Object as T;
if (t != null)
{
if (c(t))
{
a(t);
return fallThrough ? s : null;
}
}
return s;
}
}
Usage:
new Switch(foo)
.Case<Fizz>
(action => { doingSomething = FirstMethodCall(); })
.Case<Buzz>
(action => { return false; })
链接地址: http://www.djcxy.com/p/84410.html
上一篇: 用c语言编写的宏评估