A constraint cannot be a special class "System.Object"

My function requires you to pass it a string and a type as T. Based on T, I want to parse the string val as this type, but I get an error from the name of this question. Anyone who has any ideas or other ways of performing this function would be greatly appreciated.

T Parse<T>(string val) where T : System.Object
    {
        TypeCode code = Type.GetTypeCode(typeof(T));
        switch (code)
        {
            case TypeCode.Boolean:
                return System.Boolean.Parse(val);
                break;
            case TypeCode.Int32:
                return Int32.Parse(val);
                break;
            case TypeCode.Double:
                return Double.Parse(val);
                break;
            case TypeCode.String:
                return (string)val;
                break;
        }
        return null;
    }
+5
source share
1 answer

Just uninstall where T : System.Object.

Pointing out:

where T : System.Object

you say that the types Tused in your method Parseshould inherit from the object.
But, since every object in C # inherits from System.Object, you do not need this restriction (and probably one of the reasons why the compiler does not allow this).

, null, T , :

where T: class

, .

Convert.ChangeType, , generics , :

T Parse<T>(string val)
{
    return (T)Convert.ChangeType(val,typeof(T));
}
+15

All Articles