如何从C#(2.0)中的属性获取属性的名称
发布时间:2020-12-15 08:30:31 所属栏目:百科 来源:网络整理
导读:我知道我可以有一个属性,但这比我想去的工作更多……而且不够通用. 我想做点什么 class Whotsit{ private string testProp = "thingy"; public string TestProp { get { return testProp; } set { testProp = value; } }}...Whotsit whotsit = new Whotsit()
我知道我可以有一个属性,但这比我想去的工作更多……而且不够通用.
我想做点什么 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循环中.我只是好奇而已… 原始代码有字符串常量,我发现它很笨拙. 解决方法
不,没有什么可以做的.表达式whotsit.TestProp将评估该属性.你想要的是神话般的“infoof”运算符:
// I wish... MemberInfo member = infoof(whotsit.TestProp); 实际上,您只能使用反射来按名称获取属性 – 而不是代码. (当然,或者获取所有属性.虽然它仍然无法帮助您处理样本.) 一种替代方法是使用表达式树: Expression<Func<string>> = () => whotsit.TestProp; 然后检查表达式树以获取属性. 如果这些都没有帮助,也许你可以告诉我们更多你想要这个功能的原因? (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |