2011-12-25 92 views
1

我有一个一流的呼叫人:我可以使用字符串str =“id”,然后person.str = 1吗?

public class Person 
{ 
    public int id{get;set;} 
    public string name{get;set;} 
    //and many others 
} 

有没有一种方法来设置值属性不会像正规途径:person.id=1 但使用这样的string str="id"person.str=1

我想要这样,因为我有很多属性,我收到属性名称和他的价值列表。所以我想,以避免长时间switch-case及用途:

foreach(var item in MyList.Keys) 
{ 
    person.item=MyList[item]; 
} 
+0

你有属性词典吗? – dotnetstep 2011-12-25 12:32:21

回答

2
public class Person 
{ 
    public int Id{get;set;} 
    public string Name{get;set;} 
    //and many others 
} 




Dictionary<string,object> properties = new Dictionary<string,object>(); 
       properties.Add("Id",1); 
       properties.Add("Name", "TestName"); 

       Person p = new Person(); 
       foreach (KeyValuePair<string, object> obj in properties) 
       { 
        p.GetType().GetProperty(obj.Key).SetValue(p, obj.Value, null); 
       } 

这可能适用于您。确保你有适当的propertyname外壳。

+0

谢谢!!!我试了一下。 – Hadas 2011-12-25 12:39:48

+0

伟大的解决方案! 你能告诉如何以同样的方式获得价值吗? – Hadas 2011-12-25 13:33:12

+0

获得值p.GetType()。GetProperty(obj.Key,System.Reflection.BindingFlags.IgnoreCase).GetValue(p,null); ..但仔细它返回对象,你必须转换回原始类型或一些通用机能的研究。 – dotnetstep 2011-12-25 15:01:39

0

您可以使用reflection这个或dynamic类型在.NET 4.0中。

+0

我读过它,但不明白它是如何帮助我的。 ? – Hadas 2011-12-25 12:36:47

相关问题