简体   繁体   中英

C# generics and casting

I've come across a function in our code base throwing an error:

public static T InternalData<T>()
{
    return (T)"100";
}

Obviously I've simplified the code and added the "100" as a literal string value. T is of type int .

It throws a:

System.InvalidCastException: Specified cast is not valid.

It seems that you can't implicitly convert a string to int in C#, how can I fix this code so that it can handle converting any generic type?

The actual code would look something like this:

public static T InternalData<T>()
{
    return (T) something (not sure of type or data);
}

Try:

public static T InternalData<T>(object data)
{
     return (T) Convert.ChangeType(data, typeof(T));
}

This works for types that implement the IConvertible interface (which Int32 and String does).

One possibility would be to use

return (T)Convert.ChangeType(yourValue, typeof(T));

Please note that this will throw an exception, if yourValue isn't an instance of a type that implements IConvertible . It will also throw an exception if the value itself can't be converted, for example if you have "abc" instead of "100".

Use Convert.ChangeType .

public static T InternalData<T>()
{
    return (T)Convert.ChangeType("100", typeof (T));
}

It'll still throw an error if the values can't be converted, but it will not try to do a direct cast. It can convert strings to ints ok.

Do not confuse casting and converting! If the true type of an expression is not known to the compiler, eg because it is typed as object , and you know its inherent type, you can tell the C# compiler, "Hey, I know its a int , so please treat it as a int ".

 (int)expression

In your case the expression is a string expression that cannot be casted to int , simply beacuase it is not an int . However, you can convert the string to int if it represents a valid integer. Moreover the result type of your conversion is unknown because its generic. Use (T)Convert.ChangeType(...) as others have already suggested.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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