c# - 方法返回默认值

标签 c# interface return-value value-type reference-type

为什么我可以在方法声明中返回 null,它也可以返回值类型?
我认为像 IList 这样的接口(interface)对其实现的类型没有限制。
此外,如何检查返回 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/

相关文章:

c# - 处理 StreamReader.ReadLine() 中断 - 服务器不可用

c# - MySQL连接器通用SELECT多表查询方法

php - 返回空字符串或空值是否有更多优势?

java - android自定义库的架构

java - 当请求的索引越界时返回什么

c# - 如何在 EF Core 2.0 中使用 IEntityTypeConfiguration 设置 ForeignKey 和 Index 属性

c# - 如何检测客户端线程何时退出?

c# - 从工厂类返回派生类型

c++ - 模块化:是否使用接口(interface)?

interface - 可以在结构中嵌入结构以满足接口(interface)吗