? Sé que podría tener un atributo, pero eso es más trabajo de lo que quiero ... y no lo suficientemente general.¿Cómo obtengo el nombre de una propiedad de una propiedad en C# (2.0)
quiero hacer 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..
donde yo esperaría que el valor sea igual a "TestProp"
pero no puedo por la vida de mí encontrar los métodos de reflexión derecho a escribir la Método GetName ...
EDITAR: ¿Por qué quiero hacer esto? Tengo una clase para almacenar las configuraciones leídas desde una tabla 'nombre', 'valor'. Esto está poblado por un método generalizado basado en la reflexión. Me gustaría bastante para escribir la inversa ...
/// <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);
}
}
}
hacer otras modificaciones: estoy solo en el código, tener una instancia de Whotsit y quiero obtener la cadena de texto de la propiedad 'TestProp'. Parece un tanto extraño, sé que puedo usar el literal "TestProp", o en el caso de mi clase con la función datatable, estaría en un bucle foreach de PropertyInfos. Solo tenía curiosidad ...
El código original tenía constantes de cadena, lo cual me pareció torpe.
Ver http://stackoverflow.com/questions/855337/referring-to-the-property-itself-in-c-reflection-generic-type –
Es posible que tenga una respuesta aquí http://stackoverflow.com/a/1225702/661933 – nawfal