简体   繁体   English

显式强制转换运算符与T一样

[英]Explicit cast operator vs as with T

So, I came across with the following "problem" and I really curious about the reasons behind it. 因此,我遇到了以下“问题”,并且我真的对其背后的原因感到好奇。

Consider the following: 考虑以下:

public class B
{

}

public class A<T>
{
    private void AFunc(T t)
    {
        FuncRequireB((B)t); // Not allowed
        FuncRequireB(t as B); // Allowed
    }

    private void FuncRequireB(B b)
    {

    }
}

I know that the elegant solution is to define T as B at the class, but I would like to know why "(B)t" and "t as B" different in this case. 我知道一种优雅的解决方案是在课堂上将T定义为B,但是我想知道为什么在这种情况下“(B)t”和“ t as B”不同。 I know that "as" is safe, so it can generate just null if convert can not be done, and in the other hand explicit cast throws an exception if the conversion is not successful, but why the compiler should care about this? 我知道“ as”是安全的,因此如果无法完成转换,它只能生成null,另一方面,如果转换不成功,显式强制转换会引发异常,但是为什么编译器应该关心这一点? I see no difference between them in this case. 在这种情况下,我认为它们之间没有区别。

Thank you in advance! 先感谢您!

The difference is that usually a cast can perform a user-defined conversion if the compiler knows about one. 不同之处在于,如果编译器知道一个转换, 通常强制转换可以执行用户定义的转换。 For a generic type, the compiler doesn't have that information. 对于泛型类型,编译器没有该信息。 If you want to just perform a straight reference conversion cast, you can cast to object first: 如果只想执行直接参考转换转换,则可以先转换为object

FuncRequireB((B)(object) t);

This aspect of the available conversions has never been very clear to me, to be honest - but it does work. 老实说,可用转换的这方面对我来说从来都不是清楚-但它确实有效。

Note that if you can constrain T to be type compatible with B anyway, that would be cleaner. 请注意,如果您仍然可以将T约束为与B类型兼容,那会更干净。 Your type isn't very generic if bits of it will only work for a particular type argument. 如果您的类型仅适用于特定的类型参数,则它不是很通用。

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

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