2013-04-04 48 views
0

在通用方法中,我必須爲每個類型執行不同的操作。我這樣做:正確的方法比較通用類型

public static T Foo<T>(string parameter) 
    { 
      switch (typeof(T).Name) 
      { 
       case "Int32": 
        ... 
        break; 

       case "String": 
        ... 
        break; 

       case "Guid": 
        ... 
        break; 

       case "Decimal": 
        ... 
        break; 
      } 
    } 

有沒有更好的方式來知道類型T?如果(T爲int)不起作用,則爲

回答

2

這將是更好的組合使用iftypeof(<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>(...) 
} 
0

如何:

switch (Type.GetTypeCode(typeof(T))) { 
    case TypeCode.Int32: 
     break; 
    case TypeCode.String: 
     break; 
} 

這隻適用於在TypeCode枚舉中定義雖然基本類型(其中唐不包括Guid)。對於其他情況,if (typeof(T) == typeof(whatever))是檢查類型的另一種好方法。

0

創建Dictionary<Type, Action<object>

var typeDispatcher = new TypeDispatcher(); 

typeDispatcher.BringTheAction("Hello World"); 
typeDispatcher.BringTheAction(42); 
typeDispatcher.BringTheAction(DateTime.Now); 

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); 
     } 
    } 

這可以隨後通過所謂的