【问题标题】:How to assign a value to one of an object's properties if the property name is not known until runtime [duplicate]如果直到运行时才知道属性名称,如何为对象的属性之一赋值[重复]
【发布时间】:2016-11-01 02:07:12
【问题描述】:

直到运行时我才知道需要分配对象的哪个属性。

类实例是servicerecord,它有几个属性定义为字符串:

public class ServiceRecord
 {
      public ServiceRecord(){}

       public string dos1 { get; set; }
       public string dos2 { get; set; }
       public string dos3 { get; set; }
       public string dos4 { get; set; }
       <snip>
  }

假设在运行时,我发现程序需要分配一个字符串值,例如“11/2/2016”(即日期的字符串表示)给servicerecord.dos3

在 C# 中使用 System.Reflection 是如何完成的?

在 javascript 中是:servicerecord["dos3"] = ...

通过字符串引用属性的 C# 对应项是什么?

【问题讨论】:

    标签: c# system.reflection


    【解决方案1】:

    您可以使用PropertyInfo 来执行此操作。

    // Get property to write to.
    PropertyInfo pi = _serviceRecord.GetType().GetProperty("dos3");
    // Write value to property.
    pi.SetValue(_serviceRecord, stringValue, null);
    

    【讨论】:

      【解决方案2】:

      听起来你想要Dictionary&lt;string,string&gt;。记得在 ServiceRecord 的构造函数中初始化你的四个条目

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2010-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多