c# - 不能在 IEnumerable 中使用对泛型类型的约束?

标签 c#

可能已经有关于此的问题,但我无法想出搜索词来找到答案..

我可能在这里遗漏了一些明显的东西,但为什么不允许我执行以下操作,这会导致错误:

"Argument 1: cannot convert from System.Collections.Generic.IEnumerable<TType> to System.Collections.Generic.IEnumerable< Test.A>"

在调用 DoSomething 时?

public interface A
{
    void Foo();
}

public class B : A
{
    public void Foo()
    {
    }
}

class Test<TType> where TType : A
{
    public Test(IEnumerable<TType> testTypes)
    {
        DoSomething(testTypes);
    }

    void DoSomething(IEnumerable<A> someAs)
    {
    }
}

当然,这样做是可以的:

class Test
{
    public Test(IEnumerable<B> testTypes)
    {
        DoSomething(testTypes);
    }

    void DoSomething(IEnumerable<A> someAs)
    {
    }
}

最佳答案

变体仅适用于引用类型。在您的代码中,TType 也可以是值类型。如果添加 class 约束,代码将编译

class Test<TType> where TType : class, A
{
    public Test(IEnumerable<TType> testTypes)
    {
        DoSomething(testTypes);
    }

    void DoSomething(IEnumerable<A> someAs)
    {
    }
}

可以找到详细的解释here

关于c# - 不能在 IEnumerable 中使用对泛型类型的约束?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32937055/

相关文章:

c# - 查找不[可序列化]的项目

c# - Lync sdk 自动拨号

C# - 如何正确使用接口(interface)的实现

c# - 禁用隐藏字段验证

c# - monotuch UICollectionView 给出空引用错误

c# - 基础设施网格选择

c# - WinRT - TCP 客户端?

c# - 选择列表框中的所有复选框未正确显示

c# - 通过代理隧道化应用程序的所有连接

c# - 歌曲信息检索