简体   繁体   English

在属性 class 属性更改 { get; 放; }

[英]On properties class property change { get; set; }

I am having class like this:我有这样的 class :

public class MyClass<T> 
{
    public T Tag 
    { 
        get => JsonConvert.DeserializeObject<T>(_Tag); 
        set => _Tag = JsonConvert.SerializeObject(value); 
    }

    private string _Tag { get; set; }

    public void Update()
    {
        Console.WriteLine(_Tag);
    }
}

As you can see my main property is string _Tag and i need it since i am storing it into my database as jsonstring since it doesn't have same type.正如您所看到的,我的主要属性是string _Tag ,我需要它,因为我将它作为 jsonstring 存储到我的数据库中,因为它没有相同的类型。

When i do something like this:当我做这样的事情时:

MyClass<SecondClass> mc = new MyClass<SecondClass>();
SecondClass sc = new SecondClass() { someProp = "asd" };
mc.Tag = sc;
mc.Update();

then console will write what i expected to write and that is jsonString with given values of someProp: asd and it does that since Tag set is triggered when i set value to it but problem is when i do it like this:然后控制台将写入我期望写入的内容,即带有给定值的 jsonString someProp: asd并且它会这样做,因为当我为其设置值时会触发Tag set ,但问题是当我这样做时:

MyClass<SecondClass> mc = new MyClass<SecondClass>();
SecondClass sc = new SecondClass() { someProp = "asd" };
mc.Tag = sc;
mc.Update();
mc.Tag.someProp = "ddd";
mc.Update();

this time, both mc.Update() will write same output (with asd ) since second time i haven't set property but changed value of it's child class and because of that my _Tag doesn't change.这一次,两个mc.Update()都将写入相同的 output (带有asd ),因为我第二次没有设置属性,但更改了它的子 class 的值,因此我的_Tag没有改变。

So how can i overcome this?那么我该如何克服呢?

So how can i overcome this?那么我该如何克服呢?

Store the object, not it's point-in-time serialized form, and serialize it in Update :存储 object,而不是时间点序列化形式,并在Update中对其进行序列化:

public class MyClass 
{
    public T Tag {get; set;}

    public void Update()
    {
        Console.WriteLine(JsonConvert.SerializeObject(Tag));
    }
}

In general there's not a way to return a copy or derived instance from a getter, change it's properties, and have it automatically be reflected in the source of the generated instance.通常,没有办法从 getter 返回副本或派生实例、更改其属性并使其自动反映在生成实例的源中。 Alternatively you could manually set it back:或者,您可以手动将其重新设置:

var tag = mc.Tag;
tag.someProp = "ddd";
mv.Tag = tag;

Obviously it's uglier than doing it in one-line, but it's the only way to call both the getter and the setter.显然它比在一行中做更难看,但这是同时调用 getter 和 setter 的唯一方法。 You could genericize it, make it a class method (eg SetSomeProp()) that encapsulates this logic, etc.可以对其进行泛化,使其成为封装此逻辑等的 class 方法(例如 SetSomeProp())等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM