我知道我可以有一个属性,但这比我想去的工作更多……而且不够通用.
我想做点什么
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’表中读取的设置.这由基于反射的通用方法填充.我很想反写…
/// <summary> /// 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. /// </summary> /// <typeparam name="T">Type of the object to be populated.</typeparam> /// <param name="toBePopulated">The object to be populated</param> /// <param name="dataTable">'name,'value' Data table to populate the object from.</param> /// <param name="nameField">Field name of the 'name' field'.</param> /// <param name="valueField">Field name of the 'value' field.</param> /// <param name="options">Setting to control conversions - e.g. nulls as empty strings.</param> public static void PopulateFromNameValueDataTable<T> (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循环中.我只是好奇而已…
原始代码有字符串常量,我发现它很笨拙.