使用反射获取在子类的cctor上更改的继承的静态属性的值

问题描述 投票:0回答:2
public abstract class a
{
    public static string Description { get; protected set; }
}

public class b : a
{
    static b()
    {
        Description = "asdf";
    }
}

我想通过反射访问b.description(其值将为“ asdf”,但找到任何好的解决方案。

c# system.reflection
2个回答
0
投票

使用反射,必须指定所需的所有标志。

这里是样品。

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() );
}

但是,如果您详细说明用例,则解决方案可能比反思更好。


0
投票

您可以通过这种方式做到:

        // 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);

更多信息https://docs.microsoft.com/en-us/dotnet/api/system.reflection.methodbase.invoke?redirectedfrom=MSDN&view=netframework-4.8#System_Reflection_MethodBase_Invoke_System_Object_System_Object___

© www.soinside.com 2019 - 2024. All rights reserved.