Why does 'Func<IBase>' compile while 'Func<TGeneric> where TGeneric : IBase' doesn't?

旧时模样 提交于 2019-12-08 09:54:04

问题


Why is the following bloc wrong?

    public interface IBase { }
    public class ClassX : IBase
    {
    }

    public class ClassY
    {
        public static ClassX FunctionReturnX() { return new ClassX(); }
    }

    public class ClassZ<TGeneric> where TGeneric : IBase
    {
        Func<IBase> funcInterface = ClassY.FunctionReturnX; //Right

        Func<TGeneric> funcGeneric = ClassY.FunctionReturnX; //Wrong
    }

回答1:


In summary, you cannot cast ClassX to any class that implement IBase. You are only guaranteed to be able to cast it to IBase itself. Consider this example:

Imagine that you have a class ClassA that implements IBase like this:

public class ClassA : IBase
{

}

Now, ClassZ<ClassA> would look like this (this is not real code):

public class ClassZ<ClassA>
{
    Func<IBase> funcInterface = ClassY.FunctionReturnX; //Right

    Func<ClassA> funcGeneric = ClassY.FunctionReturnX; //Wrong
}

ClassY.FunctionReturnX returns ClassX which you can cast to IBase, but you cannot cast it to ClassA. Therefore, you get the complication error.




回答2:


Because ClassX is definitely a IBase, but it might not be TGeneric since something else might implement IBase and be used for TGeneric.



来源:https://stackoverflow.com/questions/36091583/why-does-funcibase-compile-while-functgeneric-where-tgeneric-ibase-doe

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!