C#: Declaring and using a list of generic classes with different types, how?

后端 未结 9 1507
猫巷女王i
猫巷女王i 2020-12-23 21:19

Having the following generic class that would contain either string, int, float, long as the type:

public class MyData         


        
9条回答
  •  猫巷女王i
    2020-12-23 22:02

    You can create a generic wrapper for SomeMethod and check for the type of the generic argument, then delegate to the appropriate method.

    public void SomeMethod(T value)
    {
        Type type = typeof(T);
    
        if (type == typeof(int))
        {
            SomeMethod((int) (object) value); // sadly we must box it...
        }
        else if (type == typeof(float))
        {
            SomeMethod((float) (object) value);
        }
        else if (type == typeof(string))
        {
            SomeMethod((string) (object) value);
        }
        else
        {
            throw new NotSupportedException(
                "SomeMethod is not supported for objects of type " + type);
        }
    }
    

提交回复
热议问题