简体   繁体   English

从类中获取所有静态属性

[英]Get all static properties from a class

I know that there are many questions like this, but I couldn't find any answer to what I'm trying to do. 我知道有很多这样的问题,但是我找不到要解决的答案。

Considering the following abstract class: 考虑以下抽象类:

public abstract class TestBase
{
    public static ITest Test => Container.Resolve<ITest>();
    public static ITest1 Test1 => Container.Resolve<ITest1>();
    public static ITest2 Test2 => Container.Resolve<ITest2>();
    public static ITest3 Test3 => Container.Resolve<ITest3>();
}

I'm trying to get all the properties that inherit from an interface IDummy like this: 我正在尝试获取从接口IDummy继承的所有属性,如下所示:

    var members = typeof(TestBase).GetMembers(BindingFlags.Static | BindingFlags.Public)
        .Where(f => f.GetType().IsAssignableFrom(typeof(IDummy)) == true);

but the list is empty. 但列表为空。 Without adding the where clause " .Where(f => f.GetType().IsAssignableFrom(typeof(IDummy)) == true) " I get all the results including the getters for the properties. 没有添加where子句“ .Where(f => f.GetType().IsAssignableFrom(typeof(IDummy)) == true) ”,我得到了所有结果,包括属性的吸气剂。

Probably is something trivial, but as I'm not so familiar with reflection I can't figure out what I'm doing wrong. 可能有些琐碎,但由于我对反射不太熟悉,因此无法弄清楚自己在做错什么。

What you get back from GetMembers is MemberInfo instances (or, for fields, FieldInfo instances). GetMembers获得的是MemberInfo实例(对于字段,则是FieldInfo实例)。 Hence, you cannot check these objects directly for being assignable from IDummy . 因此,您不能直接检查这些对象是否可从IDummy分配。

What you actually want to do is filter the MemberInfo objects for fields, then check the FieldType property of each of these objects: 您实际要做的是为字段过滤MemberInfo对象,然后检查以下每个对象的FieldType属性:

var members = typeof(TestBase).GetMembers(BindingFlags.Static | BindingFlags.Public)
    .OfType<FieldInfo>()
    .Where(f => typeof(IDummy).IsAssignableFrom(f.FieldType));

Also, note that I turned around the subject and object of the IsAssignableFrom call, as also suggested in Patrick's comment . 另外,请注意,正如Patrick的注释中所建议的那样,我转过了IsAssignableFrom调用的主题和对象。


As I just noticed, your example seems to show properties rather than fields . 正如我刚刚注意到的那样,您的示例似乎在显示属性,而不是显示field The general technique is the same, though; 但是,一般技术是相同的。 just use PropertyInfo and PropertyType rather than FieldInfo and FieldType , respectively. 分别使用PropertyInfoPropertyType而不是FieldInfoFieldType

Lastly, rather than filtering for PropertyInfo yourself, you could also use the one of the overloads of the GetProperties method directly. 最后,除了自己过滤PropertyInfo ,您还可以直接使用GetProperties方法的重载之一。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM