gpt4 book ai didi

c# - 更改 get;set; 的功能关键词

转载 作者:太空宇宙 更新时间:2023-11-03 18:24:46 25 4
gpt4 key购买 nike

<分区>

为了避免编码,我实现了一个字典来存储属性值:

 public class MainViewModel
{
public List<Person> People { get; set; }
public Person Boss { get; set; }
int i = -1;

public MainViewModel()
{
Boss = new Person() { Name = "The Boss" };
People = new List<Person>();

while (++i < 10)
{
People.Add(new Person() { Name = $"Person {i}" });
}

Update();
}

private async void Update()
{
await Task.Delay(1000);

Boss.Name = $"The Boss {++i}";

Update();
}
}

public class Person : Model
{
public string Name
{
get { return GetProperty<string>(); }
set { SetProperty(value); }
}
}


public class Model : INotifyPropertyChanged
{
private Dictionary<string, object> properties;
public event PropertyChangedEventHandler PropertyChanged;

public Model()
{
properties = new Dictionary<string, object>();
}

protected T GetProperty<T>([CallerMemberName] string key = null)
{
if(properties.ContainsKey(key))
{
return (T)properties[key];
}
return default(T);
}

protected void SetProperty<T>(T newvalue, [CallerMemberName] string key = null)
{
properties[key] = newvalue;
NotifyPropertyChanged(key);
}

public void NotifyPropertyChanged([CallerMemberName] string caller = "")
{
if (PropertyChanged != null)
{
PropertyChanged(this, new PropertyChangedEventArgs(caller));
}
}

}

如您所见,Person 模型中的 get 和 set 功能是否仅使用:

public string Name { get;set;}

对于简化代码来说真的很棒。这在某种程度上可能吗?可能在 C# 7 中?

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com