void T GetProp(T entity, string propName)
{
return entity.propName();這裡這麼寫肯定是不對的。請問怎麼寫?
}
通過反射可實現
public MainWindow()
{
InitializeComponent();
Test test = new Test();
test.Name = "TestABC";
Console.WriteLine(GetProp(test, "Name"));
}
public class Test
{
public string Name { get; set; }
}
object GetProp<T>(T entity, string propName)
{
PropertyInfo[] props = entity.GetType().GetProperties();
PropertyInfo prop = props.Where(p => p.Name == propName).FirstOrDefault();
if (prop == null)
{
return null;
}
else
{
return prop.GetValue(entity, null);
}
}