简体   繁体   English

C#泛型和铸造

[英]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. 显然我已经简化了代码并添加了“100”作为文字字符串值。 T is of type int . T的类型为int

It throws a: 它抛出一个:

System.InvalidCastException: Specified cast is not valid. System.InvalidCastException:指定的强制转换无效。

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? 看来你不能在C#中隐式地将字符串转换为int ,如何修复这段代码以便它可以处理转换任何泛型类型?

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). 这适用于实现IConvertible接口的类型( Int32String )。

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 . 请注意,如果yourValue不是实现IConvertible的类型的实例,则会抛出异常。 It will also throw an exception if the value itself can't be converted, for example if you have "abc" instead of "100". 如果值本身无法转换,它也会抛出异常,例如,如果你有“abc”而不是“100”。

Use Convert.ChangeType . 使用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. 它可以将字符串转换为int。

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 ". 如果编译器不知道表达式的真实类型,例如因为它被键入为object ,并且您知道它的固有类型,那么您可以告诉C#编译器,“嘿,我知道它是一个int ,所以请将其视为一个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 . 在你的情况下,表达式是一个字符串表达式,不能转换为int ,只是beacuase它不是一个int However, you can convert the string to int if it represents a valid integer. 但是,如果它表示有效整数,则可以将字符串转换为int Moreover the result type of your conversion is unknown because its generic. 此外,转换的结果类型未知,因为它是通用的。 Use (T)Convert.ChangeType(...) as others have already suggested. 像其他人已经建议的那样使用(T)Convert.ChangeType(...)

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

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