为什么“ Func< IBase>”在'Func< TGeneric> TGeneric:IBase哪里没有? [英] Why does 'Func<IBase>' compile while 'Func<TGeneric> where TGeneric : IBase' doesn't?

查看:67
本文介绍了为什么“ Func< IBase>”在'Func< TGeneric> TGeneric:IBase哪里没有?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下团体为什么出错?

    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
    }


推荐答案

您不能将 ClassX 强制转换为实现 IBase 的任何类。您只能保证能够将其强制转换为 IBase 本身。考虑下面的示例:

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:

想象一下,您有一个实现 IBase的类 ClassA 。 code>像这样:

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

public class ClassA : IBase
{

}

现在, ClassZ< ClassA> 看起来像这样(这不是真实的代码):

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 返回 ClassX ,您可以将其强制转换为 IBase ,但不能将其强制转换为 A类。因此,您会遇到并发症错误。

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

这篇关于为什么“ Func&lt; IBase&gt;”在'Func&lt; TGeneric&gt; TGeneric:IBase哪里没有?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆