简体   繁体   English

正确的比较通用的类型

[英]right way compare types in generic

In generic method I have to do different actions for each Type. 在通用方法中,我必须为每个类型执行不同的操作。 I do it so: 我是这样做的:

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

                case "String":
                    ...
                    break;

                case "Guid":
                    ...
                    break;

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

Is there better way to know Type T? 知道T型有更好的方法吗? if (T is int) does not work. if(T为int)不起作用。

It would be better to use if in combination with typeof(<the type to test for>) : 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>(...)
}

How about this: 这个怎么样:

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

This only works for the basic types defined in the TypeCode enumeration though (which don't include Guid ). 这仅适用于TypeCode枚举中定义的基本类型(不包括Guid )。 For other cases, if (typeof(T) == typeof(whatever) ) is another good way to check types. 对于其他情况, if (typeof(T) == typeof(whatever) )是另一种检查类型的好方法。

Create a Dictionary<Type, Action<object> : 创建一个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);
        }
    }

This can then by called by: 然后可以通过以下方式调用:

var typeDispatcher = new TypeDispatcher();

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM