Como obtenho o nome de uma propriedade de uma propriedade em C # (2.0)
Eu sei que poderia ter um atributo, mas é mais trabalho do que gostaria de ir ... e não é geral o suficiente.
Eu quero fazer algo como
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..
onde eu esperaria que o valor fosse igual a "TestProp"
mas não consigo encontrar os métodos de reflexão certos para escrever o método GetName ...
EDIT: Por que eu quero fazer isso? Eu tenho uma classe para armazenar configurações lidas em uma tabela 'nome', 'valor'. Isso é preenchido por um método generalizado baseado na reflexão. Eu gostaria muito de escrever o contrário ...
/// <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);
}
}
}
EDIÇÃO ADICIONAL: Estou apenas no código, tenho uma instância do Whotsit e quero obter a string de texto da propriedade 'TestProp'. Parece meio estranho, eu sei, posso apenas usar o literal "TestProp" - ou, no caso da minha classe para a função de dados, eu estaria em um loop foreach do PropertyInfos. Eu só estava curioso...
O código original tinha constantes de string, o que eu achei desajeitado.