[英]right way compare types in generic
在通用方法中,我必須為每個類型執行不同的操作。 我是這樣做的:
public static T Foo<T>(string parameter)
{
switch (typeof(T).Name)
{
case "Int32":
...
break;
case "String":
...
break;
case "Guid":
...
break;
case "Decimal":
...
break;
}
}
知道T型有更好的方法嗎? if(T為int)不起作用。
if
與typeof(<the type to test for>)
結合使用會更好:
if(typeof(T) == typeof(int))
{
// Foo has been called with int as parameter: Foo<int>(...)
}
else if(typeof(T) == typeof(string))
{
// Foo has been called with string as parameter: Foo<string>(...)
}
這個怎么樣:
switch (Type.GetTypeCode(typeof(T))) {
case TypeCode.Int32:
break;
case TypeCode.String:
break;
}
這僅適用於TypeCode
枚舉中定義的基本類型(不包括Guid
)。 對於其他情況, if (typeof(T) == typeof(whatever)
)是另一種檢查類型的好方法。
創建一個Dictionary<Type, Action<object>
:
class TypeDispatcher
{
private Dictionary<Type, Action<object>> _TypeDispatchers;
public TypeDispatcher()
{
_TypeDispatchers = new Dictionary<Type, Action<object>>();
// Add a method as lambda.
_TypeDispatchers.Add(typeof(String), obj => Console.WriteLine((String)obj));
// Add a method within the class.
_TypeDispatchers.Add(typeof(int), MyInt32Action);
}
private void MyInt32Action(object value)
{
// We can safely cast it, cause the dictionary
// ensures that we only get integers.
var integer = (int)value;
Console.WriteLine("Multiply by two: " + (integer * 2));
}
public void BringTheAction(object value)
{
Action<object> action;
var valueType = value.GetType();
// Check if we have something for this type to do.
if (!_TypeDispatchers.TryGetValue(valueType, out action))
{
Console.WriteLine("Unknown type: " + valueType.FullName);
}
else
{
action(value);
}
}
然后可以通過以下方式調用:
var typeDispatcher = new TypeDispatcher();
typeDispatcher.BringTheAction("Hello World");
typeDispatcher.BringTheAction(42);
typeDispatcher.BringTheAction(DateTime.Now);
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.