2013-04-04 1 views
0

En méthode générique, je dois faire différentes actions pour chaque type. Je le fais donc:à droite comparer les types génériques

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

       case "String": 
        ... 
        break; 

       case "Guid": 
        ... 
        break; 

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

Y at-il une meilleure façon de savoir type T? si (T est int) ne fonctionne pas.

Répondre

2

Il serait préférable d'utiliser if en combinaison avec 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>(...) 
} 
0

Que diriez-vous ceci:

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

Cela ne fonctionne que pour les types de base définis dans l'énumération TypeCode bien (qui don N'incluez pas Guid). Pour les autres cas, if (typeof(T) == typeof(whatever)) est un autre bon moyen de vérifier les types.

0

Créer un 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); 
     } 
    } 

Cela peut alors par appelé par:

var typeDispatcher = new TypeDispatcher(); 

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