How to get properties for inherits class

I have a Person class that inherits EntityBase :

 public class Person : EntityBase { virtual public string FirstName { get; set; } virtual public string LastName { get; set; } virtual public IList<Asset> Assets { get; set; } } 

and

 public class EntityBase : IEntity { public virtual long Id { get; protected set; } public virtual string Error { get; protected set; } } 

I need to get a list of properties of the self Person class:

 var entity = preUpdateEvent.Entity; foreach (var item in entity.GetType().GetProperties()) //only FirstName & LastName { if (item.PropertyType == typeof(String)) item.SetValue(entity, "XXXXX" ,null); } 

Now GetProperties() includes: FirstName, LastName, Id, Error , but I only need my own Person properties, namely: FirstName, LastName

How can I get properties that are defined only on Person ?

+4
source share
2 answers

Use

 var properties = typeof(Person).GetProperties(BindingFlags.Public | BindingFlags.Instance | BindingFlags.DeclaredOnly); 

The value of DeclaredOnly documented as follows:

Indicates that only members declared at the hierarchy level of the supplied type should be considered. Inherited members are not counted.

+7
source

Create a new class, such as PersonTemplate, that will only have the FirstName and LastName properties. Then:

 public PersonTemplate (Person p) { FirstName = p.FirstName; LastName = p.LastName; } 
0
source

Source: https://habr.com/ru/post/1387862/


All Articles