我知道我可以有一个属性,但这比我想去的工作更多......而且不够通用.
我想做点什么
class Whotsit { private string testProp = "thingy"; public string TestProp { get { return testProp; } set { testProp = value; } } } ... Whotsit whotsit = new Whotsit(); string value = GetName(whotsit.TestProp); //precise syntax up for grabs..
在哪里我期望价值等于"TestProp"
但我不能为我的生活找到正确的反射方法来编写GetName方法...
编辑:我为什么要这样做?我有一个类来存储从'name','value'表中读取的设置.这由基于反射的通用方法填充.我很想反写...
////// Populates an object from a datatable where the rows have columns called NameField and ValueField. /// If the property with the 'name' exists, and is not read-only, it is populated from the /// valueField. Any other columns in the dataTable are ignored. If there is no property called /// nameField it is ignored. Any properties of the object not found in the data table retain their /// original values. /// ///Type of the object to be populated. /// The object to be populated /// 'name, 'value' Data table to populate the object from. /// Field name of the 'name' field'. /// Field name of the 'value' field. /// Setting to control conversions - e.g. nulls as empty strings. public static void PopulateFromNameValueDataTable(T toBePopulated, System.Data.DataTable dataTable, string nameField, string valueField, PopulateOptions options) { Type type = typeof(T); bool nullStringsAsEmptyString = options == PopulateOptions.NullStringsAsEmptyString; foreach (DataRow dataRow in dataTable.Rows) { string name = dataRow[nameField].ToString(); System.Reflection.PropertyInfo property = type.GetProperty(name); object value = dataRow[valueField]; if (property != null) { Type propertyType = property.PropertyType; if (nullStringsAsEmptyString && (propertyType == typeof(String))) { value = TypeHelper.EmptyStringIfNull(value); } else { value = TypeHelper.DefaultIfNull(value, propertyType); } property.SetValue(toBePopulated, System.Convert.ChangeType(value, propertyType), null); } } }
进一步编辑:我只是在代码中,有一个Whotsit实例,我想得到'TestProp'属性的文本字符串.我知道这似乎有点奇怪,我可以使用文字"TestProp" - 或者在我的类的情况下使用数据表函数我将在PropertyInfos的foreach循环中.我只是好奇而已...
原始代码有字符串常量,我发现它很笨拙.
不,没有什么可以做的.表达式whotsit.TestProp
将评估属性.你想要的是神话般的"infoof"运算符:
// I wish... MemberInfo member = infoof(whotsit.TestProp);
实际上,您只能使用反射来按名称获取属性 - 而不是代码.(当然,或者获取所有属性.虽然它仍然无法帮助您处理样本.)
一种替代方法是使用表达式树:
Expression> = () => whotsit.TestProp;
然后检查表达式树以获取属性.
如果这些都没有帮助,也许你可以告诉我们更多你想要这个功能的原因?