在下面的测试代码中我不明白为什么第一行是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 的属性是非法的int
和 Func<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/