如果我知道它的字符串名称,如何为变量设置值?
问题描述:
类
public class Rule
{
public int IdRule { get;set;}
public string RuleName { get; set; }
}
我哈希表的名单与价值观。有关键的“idRule”,“ruleName”。 例
List<Hashtable> list = new Hashtable();
list["idRule"] = 1;
list["ruleName"] = "ddd";
我有功能:
private static List<T> Equaler<T>(T newRule)
{
var hashTableList = Sql.Table(NameTable.Rules); //Get table from mssql database
var list = new List<T>();
var fields = typeof (T).GetFields();
foreach (var hashtable in hashTableList)
{
var ormRow = newRule;
foreach (var field in fields)
{
???what write this???
// i need something like
//ormRow.SetValueInField(field, hashtable[field.Name])
}
list.Add(ormRow);
}
return list;
}
调用此函数:
var rules = Equaler<Rule>(new Rule())
问题:如何设定值变量,如果我知道它的字符串名称?
答
您可以使用反射来做到这一点。
string value = hashtable[field];
PropertyInfo property = typeof(Rule).GetProperty(field);
property.SetValue(ormRow, value, null);
既然你知道类型是规则,你可以使用typeof(Rule)
要获得类型的对象。但是,如果您在编译时不知道类型,则还可以使用obj.GetType()
来获取Type对象。还有一个补充性资产PropertyInfo.GetValue(obj, null)
,它允许您仅通过属性的'字符串'名称来检索值。
为什么不'typeof运算(规则).GetProperty(场)'呢? – 2013-02-27 05:03:16
@OscarMederos修正并注意到在编译时和运行时获取类型对象的区别。 – Despertar 2013-02-27 05:09:50
我的意思是在你的例子中。你仍然在调用'typeof(Rule).GetType()'而不是'typeof(Rule)'。 – 2013-02-27 05:59:22