gpt4 book ai didi

c# - 为什么这个泛型方法调用不匹配?

转载 作者:行者123 更新时间:2023-11-30 14:28:10 24 4
gpt4 key购买 nike

我有一个 Address类:

public class Address
{
//Some stuff
}

还有一个对应的*Wrapper类来强制执行某些规则使用 Address类:

public class AddressWrapper : IWrapped<Address>
{
private Address _wrapped;

public Address GetWrapped()
{
return _wrapped;
}

//And some more
}

哪里IWrapped定义为:

public interface IWrapped<T>
{
T GetWrapped();
}

我有以下用于保存这些实体的通用类(还有其他遵循这种 Entity 模式的实体和 EntityWrapper ):

public class GenericRepository
{
private GenericRepository() { }

public static void Add<T>(IWrapped<T> entity)
{
//Do something
}

public static void AddList<T>(IList<IWrapped<T>> entities)
{
//Do something
}
}

我有这个测试代码:

[Test]
public void UseGenericRepository()
{
AddressWrapper addrW = new AddressWrapper();
addrW.AddrLine1 = "x";
addrW.AddrLine2 = "y";
addrW.AddrLine3 = "z";
addrW.City = "Starling City";
//This works as expected
GenericRepository.Add<Address>(addrW);

IList<AddressWrapper> addrList = new List<AddressWrapper>();
//Fill up the addrList

//This gives error: best overloaded method match has some invalid
//arguments
GenericRepository.AddList<Address>(addrList);
}

AddressWrapped类型为 IWrapped<Address> (即,它实现它)和 Address是给 AddList 的类型参数方法,所以类型应该排队。我知道这是由于我对 C# 的了解有限generics(熟悉Java泛型),但想不通这里有什么问题--- 它应该有效。

这可能没有任何区别,但这是我的配置:

  • NHibernate 4.x
  • .NET 框架 (4.5)

最佳答案

这是因为 IList<T> 缺少类型差异. ( IList<int> 不是 IList<object> )。

使用 IEnumerable<T> ,因为它是协变的:

public static void AddList<T>(IEnumerable<IWrapped<T>> entities)
{
//Do something
}

原因:如果你得到一个 List<AddressWrapper> 的实例, 编译器不知道它是否兼容 IList<IWrapped<T>>任何可能实现.假设另一个类实现了 IWrapped<T> .写入列表时不兼容。即使您不写入 AddList 中的列表,编译器只接受兼容类型。 IEnumerable<T>不能写,所以可以变体。

与我建议对您自己的界面也使用协方差的问题无关:

public interface IWrapped<out T>

制作IWrapped<Thing>IWrapped<SpecificThing> 兼容.

MSDN:https://msdn.microsoft.com/en-us/library/ee207183.aspx

关于c# - 为什么这个泛型方法调用不匹配?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30183370/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com