简体   繁体   中英

GetProperties for inherited/child class with appropriate BindingFlags does not return expected properties

I did follow the following posts' suggestions

  1. Reflecting over all properties of an interface, including inherited ones?
  2. How do you get the all properties of a class and its base classes (up the hierarchy) with Reflection? (C#)
  3. Using GetProperties() with BindingFlags.DeclaredOnly in .NET Reflection

and modified my test to include the bindingflags as seen below.

Goal : my end goal is to test if the retrieved property is readOnly .

Issue : ChildClass/Inherited class property does not even show up on reflection.

Test to check if property exists - fails .

On GetProperties(BindingFlags.FlattenHiearchy) returns only one property which is the Result which is the parent class's property

//My failing test
Assert.NotNull(typeof(ChildClass).GetProperty("Id",BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly));

//My Alternate version which still fails
Assert.NotNull(typeof(ChildClass).GetProperty("Id",BindingFlags.FlattenHierarchy));

// My class structure against which my test is running.
class ChildClass:BaseClass<MyCustomObject>
{
   public ChildClass (Guid id)
    {
        Id = id;
    }

    public readonly Guid Id;
}

class BaseClass<T>:IMyInterFace<T>
{
     public T Result { get; private set; }
}

public interface IMyInterFace<T>
{
    T Result { get; }

}

EDIT 9/14/2016 I apologize I missed the fact that I actually did know or understand I can Assert.NotNull if i say GetField - but that wouldnt help me achieve the end goal - to check if it is readonly - I am now unsure as to if this is even possible can someone confirm? thanks!.

public readonly Guid Id is a field , not a property. Use the GetField method instead:

typeof(ChildClass).GetField("Id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);

You can check to see if it is readonly by looking at the IsInitOnly property of the FieldInfo class.

var result = typeof(ChildClass).GetField("Id", BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly);
Assert.IsTrue(result.IsInitOnly);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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