问题描述
为什么允许我在方法声明中返回 null,它也可以返回值类型?
我认为 IList
此外,如何检查返回 IList
public IList<int> SomeMethod()
{
// Allowed
return new MyStructList();
// Allowed
return null;
}
public struct MyStructList : IList<int>
{
...
}
解决方法
您的 SomeMethod
方法返回一个 IList<int>
。 IList<T>
是一个接口,它是一种引用类型。 null
是引用类型的允许值。
当你做 return new MyStructList()
时,这基本上是:
IList<int> ret = new MyStructList();
return ret;
那个IList<int> ret = new MyStructList();
盒MyStructList()
:为它分配一个盒,将MyStructList
复制到盒中,并创建对盒的引用并将其分配给{{1} }.这是必要的,因为 ret
的类型为 ret
,而 IList<int>
是引用类型,所以 IList<T>
只能包含引用。