public abstract class a
{
public static string Description { get; protected set; }
}
public class b : a
{
static b()
{
Description = "asdf";
}
}
我想通过反射访问b.description(其值将为“ asdf”,但找到任何好的解决方案。
使用反射,必须指定所需的所有标志。
这里是样品。
private void button1_Click( object sender, EventArgs e )
{
b obj = new b();
var props = obj.GetType().GetProperties( BindingFlags.Public );
var prop = obj.GetType().GetProperty( "Description",
BindingFlags.Static |
BindingFlags.FlattenHierarchy |
BindingFlags.Public
);
MessageBox.Show( prop.GetValue( obj, null ).ToString() );
}
但是,如果您详细说明用例,则解决方案可能比反思更好。
您可以通过这种方式做到:
// Get a PropertyInfo of specific property type(T).GetProperty(....)
PropertyInfo propertyInfo;
propertyInfo = typeof(b)
.GetProperty("Description", BindingFlags.Public | BindingFlags.Static| BindingFlags.FlattenHierarchy);
// Use the PropertyInfo to retrieve the value from the type by not passing in an instance
object value = propertyInfo.GetValue(null, null);