我知道我可以擁有一個屬性,但這比我想去的工作要多...而且不夠通用。如何從C#中的屬性獲取房產的名稱(2.0)
我要像做
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方法...
編輯:我爲什麼要這樣做?我有一個類來存儲從「名稱」,「值」表讀取的設置。這是通過基於反思的廣義方法來填充的。我很喜歡寫反...
/// <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」 - 或者在我的類的情況下datatable函數我會在PropertyInfos的foreach循環。我只是好奇...
原始代碼有字符串常量,我發現笨拙。
見http://stackoverflow.com/questions/855337/referring-to-the-property-itself-in-c-reflection-generic-type – 2009-05-13 15:45:11
你可能在這裏回答http://stackoverflow.com/a/1225702/661933 – nawfal 2013-04-27 14:51:30