简体   繁体   中英

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. 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? 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:

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. Your type isn't very generic if bits of it will only work for a particular type argument.

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