这是我已经困惑了很长一段时间的事情。我不确定这是C#特有的问题,还是我不能理解的简单的OOP事实。
IList<IList<int>> result = new List<IList<int>>(); //Works Fine
IList<IList<int>> result2 = new IList<IList<int>>(); //Gives Error because we cannot initialize interface
IList<IList<int>> result3 = new List<List<int>>(); //Gives Error please explain why
IList<IList<int>> result4 = new IList<List<int>>(); //Gives Error please explain why对于上面的代码行,有人能解释一下为什么第3行和第4行是错误的,而第1行是正确的吗?
发布于 2020-02-01 05:52:41
因为在
R<S> = T<U>;T : R.您的所有示例都满足这一点。List : IList、List = List和IList = IList.T : new().这会取消2和4.U = S.中的接口的资格泛型类型必须匹配,不可派生。这取消了3.的资格
因为U= S,所以写成这样
R<S> = new T<S>;那就更清楚了。这四个将满足上述要求。
IList<IList<int>> result = new List<IList<int>>();
List<IList<int>> result2 = new List<IList<int>>();
IList<List<int>> result3 = new List<List<int>>();
List<List<int>> result4 = new List<List<int>>(); 发布于 2020-02-01 05:31:01
IList<int>和IList<IList<int>>不是一回事。您不能将一个赋值给另一个,就像您不能将字符串赋值给int一样。
而且它的语法也很古怪。每个<都需要一个>,反之亦然。
如果你真的想这样做,你需要
List<List<int>> result = new List<List<int>>();请注意,我们实例化的是具体类型,而不是接口。
https://stackoverflow.com/questions/60011398
复制相似问题