首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >变量名的字符串

变量名的字符串
EN

Stack Overflow用户
提问于 2009-08-18 12:36:43
回答 3查看 54.5K关注 0票数 16

我有一个类(Customer),它拥有超过200个字符串变量作为属性。我使用带有key和value参数的方法。我尝试从xml文件中提供键和值。为此,value必须替换为Customer类的属性(字符串变量)。

代码语言:javascript
复制
Customer
{
  public string Name{return _name};

  public string Address{return _address};
}


CallInput
{
  StringTempelate tempelate = new StringTempelate();
  foreach(item in items)
  tempelate .SetAttribure(item.key, item.Value -->   //Say this value is Name, so it has to substitute Customer.Name
}

有可能吗?

EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2009-08-18 12:42:17

您可以使用反射来“按名称”设置属性。

代码语言:javascript
复制
using System.Reflection;
...
myCustomer.GetType().GetProperty(item.Key).SetValue(myCustomer, item.Value, null);

您还可以使用GetValue读取属性,或者使用GetType().GetProperties()获取所有属性名称的列表,该方法返回一个PropertyInfo数组( Name属性包含属性名称)

票数 23
EN

Stack Overflow用户

发布于 2009-08-18 12:56:41

反射是一个选项,但是200个属性是...很多。碰巧的是,我目前正在做类似的事情,但是类是由code-gen创建的。为了适应“按名称”的用法,我添加了一个索引器(在代码生成阶段):

代码语言:javascript
复制
public object this[string propertyName] {
    get {
        switch(propertyName) {
            /* these are dynamic based on the the feed */
            case "Name": return Name;
            case "DateOfBirth": return DateOfBirth;
            ... etc ...
            /* fixed default */
            default: throw new ArgumentException("propertyName");
        }
    }
}

这提供了“按名称”的便利性,但具有良好的性能。

票数 5
EN

Stack Overflow用户

发布于 2009-08-18 12:45:45

使用反射和字典对象作为items集合。

代码语言:javascript
复制
Dictionary<string,string> customerProps = new Dictionary<string,string>();
Customer myCustomer = new Customer(); //Or however you're getting a customer object

foreach (PropertyInfo p in typeof(Customer).GetProperties())
{
    customerProps.Add(p.Name, p.GetValue(customer, null));
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/1293549

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档