演员表< T>列出<接口>演员表、接口、LT、GT

2023-09-02 01:33:44 作者:且听风吟

public interface IDic
{
    int Id { get; set; }
    string Name { get; set; }
}
public class Client : IDic
{

}

我怎么能投名单,其中,客户端> 名单,其中,IDIC>

推荐答案

您不能的铸造的它(preserving参考身份) - 这将是不安全的。例如:

You can't cast it (preserving reference identity) - that would be unsafe. For example:

public interface IFruit {}

public class Apple : IFruit {}
public class Banana : IFruit {}

...

List<Apple> apples = new List<Apple>();
List<IFruit> fruit = apples; // Fortunately not allowed
fruit.Add(new Banana());

// Eek - it's a banana!
Apple apple = apples[0];

现在你可以将一个名单,其中,苹果&GT; 的IEnumerable&LT; IFruit&GT; 在.NET 4.0 / C# 4,由于协方差,但如果你想有一个名单,其中,IFruit&GT; 你必须创建一个新列表中。例如:

Now you can convert a List<Apple> to an IEnumerable<IFruit> in .NET 4 / C# 4 due to covariance, but if you want a List<IFruit> you'd have to create a new list. For example:

// In .NET 4, using the covariance of IEnumerable<T>
List<IFruit> fruit = apples.ToList<IFruit>();

// In .NET 3.5
List<IFruit> fruit = apples.Cast<IFruit>().ToList();

但是,这是的没有的同铸原始列表 - 因为现在有两个的单独的的列表。这是安全的,但你要明白,改变一个列表的不会的在其他列表中看到制作。 (修改了的对象的是,名单是指将被视为当然。)

But this is not the same as casting the original list - because now there are two separate lists. This is safe, but you need to understand that changes made to one list won't be seen in the other list. (Modifications to the objects that the lists refer to will be seen, of course.)