How to map fields in an object to another dynamically?

I have two objects with attributes:

Object 1:

Person

  • Name
  • Location
  • Age
  • Address

Object 2:

PersonRule

  • Personname
  • Person location
  • The character

PersonRule is controlled by a user interface that sets a user rule (it can also set a lot), and the user says what name, location, age should be in the rule. This rule must be mapped to a person if the person has the same value for the attributes.

I can do a simple equality check, but itโ€™s also possible that in the future a new attribute is added to the personโ€™s rule, something like personaddress. Then I need to check if the rule matches the character by accepting the address of the person.

Is there a way to build something like matching all personrule attributes for a person, so that I donโ€™t need to make changes when a new attribute is added to the rule? Of course, this assumes that the corresponding attribute is available in the person object.

Thanks, -Mike

+4
source share
2 answers

You can use one of the available object-object mapping libraries, for example AutoMapper or EmitMapper . They will take care of copying data from the Person instance to the PersonRule instance, which can be compared to another PersonRule instance. For example, with EmitMapper, your code might look like this:

var config = new DefaultMapConfig().MatchMembers((m1, m2) => "Person" + m1 == m2); ObjectMapperManager.DefaultInstance .GetMapper<Person, PersonRule>(config) .Map(person, personRule); 
+8
source

It seems that you are looking for reflection , see this example question:

How to get a list of class properties?

0
source

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


All Articles