C# 对象初始化程序将初始化只读属性,但仅适用于非原始类型

标签 c# primitive-types reference-type object-initializers

在下面的测试代码中我不明白为什么第一行是TestMethod是合法的,但剩下的两行是不合法的:

public class Bar
{
    public string Prop { get; set; }
}

public class Foo
{
    public int Primitive { get; } = 0;
    public Func<int, int> Function { get; } = (i) => i;
    public Bar Bar { get; } = new Bar();
}

public class TestClass
{
    public void TestMethod()
    {
        var baz = new Foo { Bar = { Prop = "Hello World!" } }; // legal
        var buzz = new Foo { Primitive = 1 }; // Property or indexer 'Foo.Primitive' cannot be assigned to -- it is read only
        var fuzz = new Foo { Function = (i) => 2 }; // Property or indexer 'Foo.Function' cannot be assigned to -- it is read only
    }
}

如果分配给类类型的只读属性是合法的,例如 Bar在对象初始值设定项中(它是;这是有道理的,因为据我所知,在 C# 中,“只读”实际上意味着“除了在类构造时只读”)那么为什么分配给类型为 like 的属性是非法的intFunc<int, int>

这似乎更加令人困惑,因为(据我所知)Func<int, int>是引用类型,如 Bar属性,但不同于 int属性(property)。

最佳答案

var baz = new Foo { Bar = { Prop = "Hello World!" } }; // legal

这不是对 Bar赋值。它本质上是:

var tmp = new Foo();
tmp.Bar.Prop = "Hello World!";
var baz = tmp;

.Bar 没有分配给.

然而,相反地:

var buzz = new Foo { Primitive = 1 };

是:

var tmp = new Foo();
tmp.Primitive = 1;
var buzz = tmp;

分配给 .Primitive

关于C# 对象初始化程序将初始化只读属性,但仅适用于非原始类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55935265/

相关文章:

C# 如何找到引用类型的大小

c# - .NET 字符串和引用类型参数

c# - C# 教学引用

javascript - 将数据从 JavaScript 文件发送到另一个 JavaScript 文件

c# - 是否可以在运行时获取类摘要?

java - 为什么人们仍然在 Java 中使用原始类型?

c++ - Linux 数据模型和原始类型大小

c# - 在 Excel 中调用 WCF 方法切换 "context"并让 Word 继续 "work"

c# - 创建组合命令行/Windows 服务应用

java - 将 getByte() 与原始数据一起使用