如果 属性 名称直到运行时才知道,如何为对象的其中一个属性赋值
How to assign a value to one of an object's properties if the property name is not known until runtime
直到运行时我才知道我的对象的哪个 属性 需要分配。
class 实例是 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# 对应物是什么?
您可以使用 PropertyInfo 来执行此操作。
// Get property to write to.
PropertyInfo pi = _serviceRecord.GetType().GetProperty("dos3");
// Write value to property.
pi.SetValue(_serviceRecord, stringValue, null);
我觉得你想要 Dictionary<string,string>
。请记住在 ServiceRecord 的构造函数中初始化您的四个条目
直到运行时我才知道我的对象的哪个 属性 需要分配。
class 实例是 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# 对应物是什么?
您可以使用 PropertyInfo 来执行此操作。
// Get property to write to.
PropertyInfo pi = _serviceRecord.GetType().GetProperty("dos3");
// Write value to property.
pi.SetValue(_serviceRecord, stringValue, null);
我觉得你想要 Dictionary<string,string>
。请记住在 ServiceRecord 的构造函数中初始化您的四个条目