使用像构造函数这样的卷曲括号将新值设置为基本对象



在修改现有实例时,如何使用对象构造器的卷发括号?

我在构造函数中尝试了浅和深的复印,但是似乎没有一种方法可以将this与所需的对象实例交换,或者一种简单可靠的方法来设置所有(在期间不断变化)开发)构造函数内部的字段和属性。

您可以在这里看到,与旧的get { return ... }相比,卷曲括号节省了很多空间:

public static MyClass MyClass1 => new MyClass()
{
    Property1 = 20,
    Property2 = "some text",
    Property3 = new MyOtherClass(MyEnum.Something)
};

基本上是相同的代码,但具有额外的5行:

public static MyClass MyClass2
{
    get
    {
        var instance = new MyClass(); // or it could be  = MyClass1;
        instance.Property1 = 42;
        instance.Property2 = "some other text";
        instance.Property3 = new MyOtherClass(MyEnum.SomethingElse);
        return instance;
    }
}

我的目标是使用卷曲括号设置基本对象的新属性值(无继承或手动执行构造函数中的浅/深拷贝)来保存所有垂直空间。我该怎么做?

我经常使用完整的文档自动编制,因此请手动格式化代码并不触摸它行不通。

我试图解决的问题: get { ... }- typyle getter在自动格式时占用5行代码。=>-样式Getter更加紧凑,我想找到一种使用它的方法。

弄清楚了:

public class MyClass
{
    public MyClass() { }
    public MyClass(MyClass baseInstance)
    {
        var fields = typeof(MapObject).GetFields();
        foreach (var field in fields)
            field.SetValue(this, field.GetValue(baseInstance));
        var props = typeof(BaseItems).GetProperties();
        foreach (var prop in props)
            if (prop.CanWrite)
                prop.SetValue(this, prop.GetValue(baseInstance));
    }
}

…让您这样做:

public static MyClass MyClass2 => new MyClass(MyClass1)
{
    Property1 = 42,
    Property2 = "some other text",
    Property3 = new MyOtherClass(MyEnum.SomethingElse)
};

这不是理想的,但对我有用。

您是否尝试使用属性?

class MyClass()
        {
            private int myInt;
            public int MyInt { get; set; }
        }

最新更新