I am having class like this:
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.
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:
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.
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
:
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. 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. You could genericize it, make it a class method (eg SetSomeProp()) that encapsulates this logic, etc.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.