正确的比较通用的类型

时间:2013-04-04 10:40:54

标签: c# generics

在通用方法中,我必须为每个类型执行不同的操作。我是这样做的:

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)不起作用。

3 个答案:

答案 0 :(得分: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>(...)
}

答案 1 :(得分:0)

这个怎么样:

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

这仅适用于TypeCode枚举中定义的基本类型(不包括Guid)。对于其他情况,if (typeof(T) == typeof(whatever))是检查类型的另一种好方法。

答案 2 :(得分:0)

创建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);