我几天来一直在争论协方差和逆变,我想我已经理解了一些东西,但我希望我能得到确认,因为我目前的研究无法得到肯定或没有答案.我有以下类层次结构:
class Shape
{
public string Name { get; set; }
}
class Square : Shape
{
}
Run Code Online (Sandbox Code Playgroud)
然后,这就是我从程序开始的内容:
List<Square> squares = new List<Square>() { new Square { Name = "Square One" }, new Square { Name = "Square Two" } };
IEnumerable<Square> squaresEnum = squares;
Run Code Online (Sandbox Code Playgroud)
现在有两个问题:
以下是可能的,因为IEnumerable <T> IS协变:
IEnumerable<Shape> shapesEnumerable = squares;
Run Code Online (Sandbox Code Playgroud)
AND,以下是不可能的,因为List <T>不是协变的:
List<Shape> shapes = squares;
Run Code Online (Sandbox Code Playgroud)
如果需要,可以使用以下完整的程序代码:
class Program
{
static void Main(string[] args)
{
List<Square> squares = new List<Square>() { new Square { Name = …Run Code Online (Sandbox Code Playgroud) 我正在努力了解处理对象和垃圾收集.特别是,我不明白为什么我仍然可以使用处置对象.我不是想做任何实际的事情,我现在只是在玩理论,在我的理解中,我认为我无法做到以下几点:
class Program
{
static void Main(string[] args)
{
Person p = new Person();
using (p)
{
p.Name = "I am Name";
}
Console.WriteLine(p.Name); // I thought this would break because I've already disposed of p
Console.ReadLine();
}
}
public class Person : IDisposable
{
public string Name;
public void Dispose()
{
Console.WriteLine("I got killed...");
}
}
Run Code Online (Sandbox Code Playgroud)
我希望有人可以在这里给我一些指导或指导,以便澄清我对这个概念的误解?