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 型吗?if (T is int)不起作用。

4

3 回答 3

2

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>(...)
}
于 2013-04-04T10:44:47.497 回答
0

这个怎么样:

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

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

于 2013-04-04T10:46:32.470 回答
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);
于 2013-04-04T10:47:07.270 回答