简体   繁体   中英

Could not get the properties of a generic type by using reflection

I am simplyfing the question here, so the example could not make any sence for the real world.

public class BusinessEntity<T>
{
    public int Id {get; set;}
}

public class Customer : BusinessEntity<Customer>
{

    public string FirstName { get; set;}
    public string LastName { get; set;}
}

When I try to get Customer class properties by reflection, I could not get the properties of the generic base class. How to get Id from the BusinessEntity ?

Type type = typeof(Customer);

PropertyInfo[] properties = type.GetProperties(); 
// Just FirstName and LastName listed here. I also need Id here 

Nope, that definitely returns all 3 properties. Check that in your real code, whether Id is internal / protected / etc (ie non-public). If it is, you'll need to pass in BindingFlags , for example:

PropertyInfo[] properties = type.GetProperties(
    BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

(the default is public + instance + static)

Also check that it isn't a field in your actual code; if it is:

public int Id;

then it is a field, and you should use GetFields make Id a property ;p

In order to get the base properties you will have to use the BaseType property of the Type

PropertyInfo[] baseProperties = typeof(Customer).BaseType.GetProperties(BindingFlags.DeclaredOnly);
PropertyInfo[] properties = typeof(Customer).GetProperties(); 

What is the issue, your code is perfectly fine and returning the correct properties

Type type = typeof(Customer);
PropertyInfo[] properties = type.GetProperties(); 
foreach(var prop in properties)
{ Console.WriteLine(prop) }

Result

System.String FirstName 
System.String LastName 
Int32 Id

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