方法返回默认值

为什么允许我在方法声明中返回 null,它也可以返回值类型?
我认为 IList 之类的接口对其实现的类型没有限制。
此外,如何检查返回 IList 的方法是否返回默认值?

public IList<int> SomeMethod()
{
    // Allowed
    return new MyStructList();

    // Allowed
    return null;
}

public struct MyStructList : IList<int>
{
   ...
}
iCMS 回答:方法返回默认值

您的 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> 只能包含引用。

本文链接:https://www.f2er.com/142383.html

大家都在问