gpt4 book ai didi

c# - Dynamically Flat C# object class 运行时的属性列表

转载 作者:太空宇宙 更新时间:2023-11-03 23:29:15 26 4
gpt4 key购买 nike

我有一个这样的 A 类:

public class A
{
private String id; // Generated on server
private DateTime timestamp;
private int trash;
private Humanity.FeedTypeEnum feedType
private List<Property> properties;
// ...

哪里Property是:

public class Property
{
private Humanity.PropertyTypeEnum type;
private string key;
private object value;
//...

我想构建一个扁平的动态对象 List<Property> properties A 的字段到原始属性。例如:

A a = new A();
a.Id = "Id";
a.Timestamp = DateTime.Now;
a.Trash = 2;
a.FeedType = Humanity.FeedTypeEnum.Mail;
a.Properties = new List<Property>()
{
new Property()
{
Type = Humanity.PropertyTypeEnum.String,
Key = "name"
Value = "file1.pdf"
},
new Property()
{
Type = Humanity.PropertyTypeEnum.Timestamp,
Key = "creationDate",
Value = Datetime.Now
}
}

正如我评论过的,我想把这个 a 弄平对象以便访问属性:

String name = a.Name;
DateTime creationDate = a.CreationDate;
a.Name = "otherName";
a.CreationDate = creationDate.AddDays(1);

我已经使用反射实现了这一点。但是,我发现这是使用 ExpandoObject 的最佳选择。 .

问题是,我如何使用 ExpandoObject 来做到这一点?类(class)?

最佳答案

您可以扩展DynamicObject 类做您想做的事情:

class A : System.Dynamic.DynamicObject
{
// Other members
public List<Property> properties;

private readonly Dictionary<string, object> _membersDict = new Dictionary<string, object>();

public override bool TryGetMember(System.Dynamic.GetMemberBinder binder, out object result)
{
result = null;
if (!_membersDict.ContainsKey(binder.Name))
return false;

result = _membersDict[binder.Name];
return true;
}

public override bool TrySetMember(System.Dynamic.SetMemberBinder binder, object value)
{
if (!_membersDict.ContainsKey(binder.Name))
return false;

_membersDict[binder.Name] = value;
return true;
}

public void CreateProperties()
{
foreach (Property prop in properties)
{
if (!_membersDict.ContainsKey(prop.key))
{
_membersDict.Add(prop.key, prop.value);
}
}
}
}

然后像这样使用它:

A a = new A();
/////////
a.Properties = new List<Property>()
{
new Property()
{
Type = Humanity.PropertyTypeEnum.String, // Now this property is useless, the value field has already a type, if you want you can add some logic around with this property to ensure that value will always be the same type
Key = "name"
Value = "file1.pdf"
},
new Property()
{
Type = Humanity.PropertyTypeEnum.Timestamp,
Key = "creationDate",
Value = Datetime.Now
}
}
a.CreateProperties();
dynamic dynA = a;
dynA.name = "value1";

关于c# - Dynamically Flat C# object class 运行时的属性列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32869080/

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