C# 有人可以向我解释一下这是如何工作的吗?

问题描述 投票:0回答:1

不太确定这是如何运作的。 甚至不知道如何在构建 Child 类时使用对象初始值设定项。 然后它如何覆盖我的默认测试类。

    internal class Program
    {
        static void Main(string[] args)
        {
            Child child = new Child
            {
                Test = { Name = "hello" }
            };

            //child.Test.Name prints out "hello"
        }
    }

    public class Child : Parent
    {
        public Child()
        {

        }

    }
    public abstract class Parent
    {
        public Test Test { get; }

        protected Parent()
        {
            Test = new Test { Name = "Default" };
        }
    }

    public class Test
    {
        public string Name { get; set; }
    }

预期会出现错误,我不应该在测试中使用对象初始值设定项,并且默认值无法更改。

c#
1个回答
0
投票

这类似于:

Child child = new Child();
child.Test.Name = "hello";

这没有什么违法的。

可以说有点不清楚什么时候是通过

set
进行分配,什么时候是通过
get
进行变异,但这里的线索是缺少
new
;只需使用
= {...}
即可通过
get

© www.soinside.com 2019 - 2024. All rights reserved.