C#get和set可通过属性变量名 [英] C# get and set property by variable name

查看:554
本文介绍了C#get和set可通过属性变量名的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有办法做到这一点?我尝试测试如果一个对象的属性存在,并且如果是这样,我想将值设置为它。 (可能是完整的想法是不好的,如果是真的 - 为什么)

 类信息
{
公串X1 {设置;得到; }
公共字符串X2 {设置;得到; }
公共字符串X3 {设置;得到; }
}

&字典LT;字符串,字符串>值=新词典<字符串,字符串>();
values.Add(X1,blah1);
values.Add(X2,blah2);
values.Add(notthere的,blah3);

信息信息=新信息();

的foreach(中值VAR项)
{
字符串参数propertyName = item.Key;
字符串值= item.Value;
如果(!info.GetType()的getProperty(propertyName的)= NULL)//这可能适用
{
info.propertyName =价值; //这不,如何设置呢?
}
}


解决方案

是的,你找 PropertyInfo.SetValue 方法如

  VAR propInfo = info.GetType()的getProperty(propertyName的)。 
如果(propInfo!= NULL)
{
propInfo.SetValue(资讯,值null);
}


Is there any way to do this? I try to test if a property of an object exists and if it does, I want to set a value to it. (Maybe the complete idea is bad, if true - why?)

class Info
{
    public string X1{ set; get; }
    public string X2{ set; get; }
    public string X3{ set; get; }
}

Dictionary<string, string> values = new Dictionary<string, string>();
values.Add("X1","blah1");
values.Add("X2","blah2");
values.Add("NotThere","blah3");

Info info = new Info();

foreach (var item in values)
{
  string propertyName = item.Key;
  string value = item.Value;
  if (info.GetType().GetProperty(propertyName) != null)  //this probably works
  {
        info.propertyName = value; //this doesn't, how to set it?
  }
}

解决方案

Yes, your looking for the PropertyInfo.SetValue method e.g.

var propInfo = info.GetType().GetProperty(propertyName);
if (propInfo != null)
{
    propInfo.SetValue(info, value, null);
}

这篇关于C#get和set可通过属性变量名的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆