質問

I'm using reflection in a PCL project (4.5, profile 78). The reflection api has changed in 4.5 (see Evolving the reflection API), and event though that change is barely noticeable in the classic framework (where TypeInfo inherits from Type) it's something else for other profiles, including PCL.

In .NET 4, this would retrieve all the public members:

typeof(MyType).GetMembers ();

The rough equivalent in .NET 4.5 is

typeof (MyType).GetTypeInfo ().DeclaredMembers;

except that it returns all the members. The doc says

To filter the results of the DeclaredMembers property, use LINQ queries.

Well. I'd like to, but MemberInfo does not provide the IsStatic, IsPrivate, ... properties. It looks like those properties are only defined in ConstructorInfo, FieldInfo, MethodInfo but are missing in (base) MemberInfo, PropertyInfo and EventInfo.

Is there something I'm missing ? How should filter the MemberInfo and the PropertyInfo

役に立ちましたか?

解決

One way retrieve the accessibility accessors on PropertyInfo is

bool HasPublicGetter (PropertyInfo pi) 
{
    if (!pi.CanRead)
        return false;
    MethodInfo getter = pi.GetMethod;
    return getter.IsPublic;
}

Same applies to EventInfo with AddMethod.

It all make sense, as properties aren't public or private by themselves, but have public or private getters and setters.

他のヒント

The GetMembers and DeclaredMembers are not the same, the DeclaredMembers ignores inherited members. You can do the same with GetMembers using BindingFlags.DeclaredOnly like this: GetMembers(BindingFlags.DeclaredOnly | BindingFlags.Public | BindingFlags.Instance | BindingFlags.Static);

ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top