为什么我可以在方法声明中返回 null,它也可以返回值类型?
我认为像 IList
此外,如何检查返回 IList
public IList<int> SomeMethod()
{
// Allowed
return new MyStructList();
// Allowed
return null;
}
public struct MyStructList : IList<int>
{
...
}
最佳答案
您的SomeMethod
方法返回 IList<int>
。 IList<T>
是一个接口(interface),它是一个引用类型。 null
是引用类型的允许值。
当你这样做时return new MyStructList()
,这本质上是以下内容的简写:
IList<int> ret = new MyStructList();
return ret;
那个IList<int> ret = new MyStructList();
盒MyStructList()
:为其分配了一个框,MyStructList
被复制到框中,并创建对该框的引用并将其分配给 ret
。这是必要的,如ret
类型为IList<int>
,和IList<T>
是一个引用类型,所以 ret
只能包含引用。
关于c# - 方法返回默认值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68268543/