Tuesday, January 2, 2018

c How to check and set values of specific value object inside a generic class

c How to check and set values of specific value object inside a generic class




c# - How to check and set values of specific value object inside a generic class? -

i have method in repository class sets insert metadata domain object:

private void setinsertmetadata(tdomainentity entity) { entity.insertdt = datetime.utcnow; }

i need check � entity class have list of value objects properties? if so, set insertdt in each of them.

how do check generic class?

making assumptions here. first interface looks this:

public interface tdomainentity { datetime insertdt { get; set; } }

and have couple of entities:

public class entitya : tdomainentity { public entityb bvalue { get; set; } public datetime insertdt { get; set; } } public class entityb : tdomainentity { public datetime insertdt { get; set; } }

your function loop through every property , set insertdt property this:

private void setinsertmetadata(tdomainentity entity) { if(entity == null) return; //to prevent errors below entity.insertdt = datetime.utcnow; //get properties of entity implement tdomainentity interface var props = entity.gettype().getproperties() .where(p => typeof(tdomainentity).isassignablefrom(p.propertytype)); //recurse through each property: foreach(var p in props) { setinsertmetadata((tdomainentity)p.getvalue(entity)); } }

or merge lastly lines together:

entity.gettype().getproperties() .where(p => typeof(tdomainentity).isassignablefrom(p.propertytype)) .tolist() .foreach(p => setinsertmetadata((tdomainentity)p.getvalue(entity)));

if want includeienumerable<tdomainentity> properties, add together this:

entity.gettype().getproperties() .where(p => typeof(ienumerable<tdomainentity>).isassignablefrom(p.propertytype)) .tolist() .foreach(p => { var value = (ienumerable<tdomainentity>)p.getvalue(entity); if(value == null) return; value.tolist().foreach(i => setinsertmetadata((tdomainentity)i)); });

c# .net generics reflection

go to link download
download
alternative link download

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.