在C#中
给定像{id:'1',name:'foo'}这样的哈希表

如何动态创建具有相同成员的类的实例?

public class product {
    public int id;
    public string name;
}


我知道我会遇到问题,但是稍后会解决。现在,我什至无法基于哈希表的键访问类的成员。我要这样做正确吗?

这就是我目前正在使用的方法。

product p = new product();
Type description = typeof(product);
foreach (DictionaryEntry d in productHash)
{
    MemberInfo[] info = description.GetMember((string)d.Key);
    //how do  I access the member of p based on the memberInfo I have?
    //p.<?> = d.Value;
}


谢谢

最佳答案

首先,您需要将成员作为属性访问。然后,您可以向属性询问特定实例的值:

PropertyInfo property = description.GetProperty((string) d.Key);

object value = property.GetValue(p, null);


第二个参数是索引,仅当属性为indexer时才会生效。

关于c# - 从哈希表C#创建对象,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/4307148/

10-17 01:56