Look at a colleague using an ORM framework that has the ability to dynamically assign values between two class objects through the functionality of attributes (attached properties)
I think this is a good function, but the ORM used by my colleagues is not the Dapper I use, so I wrote a tool class that implements the same function.
Send a sticker for other people who have this need to make a reference. I hope you will put forward some more opinions.
usingSystem;usingSystem.Collections.Generic;usingSystem.Linq;usingSystem.Reflection;usingSystem.Runtime.InteropServices;usingSystem.Text;usingSystem.Threading.Tasks;usingSystem.Xml.Serialization;namespaceconsoleapplication2{classProgram {Static voidMain (string[] args) {Animaltypetestclass TestClass=NewAnimaltypetestclass () { age="1", Name="2"}; Na a= (Na) classtohellp.map<na>(TestClass); Console.WriteLine (A.myage); Console.WriteLine (A.myname); } } Public classCLASSTOHELLP { Public Static ObjectMap<t> (ObjectOswhereT:class,New() { //converted Classes vart =NewT (); varFieldinfos =T.gettype (). GetFields (); foreach(varMInfoinchOS. GetType (). GetFields ()) {varMinfovalue =minfo.getvalue (OS); if(Minfovalue = =NULL) Continue; foreach(varFieldinchattribute.getcustomattributes (mInfo). Where (attr= = attr. GetType () = =typeof(Objecttotypeattribute)). SelectMany (attr= = fieldinfos.where (field = field. Name = =((Objecttotypeattribute) attr). field)) {field. SetValue (t, Minfovalue); } } returnT; }} [AttributeUsage (Attributetargets.field)] Public classObjecttotypeattribute:attribute { Public stringField {Get;Set; } PublicObjecttotypeattribute (stringPet) {Field=Pet; } } Public classAnimaltypetestclass {[Objecttotype ("MyName")] Public stringName; [Objecttotype ("MyAge")] Public stringAge ; } Public classNa { Public stringMyName; Public stringMyAge; }}
Please do not use the reflection efficiency problem with the groove. The efficiency of reflection is still high without loading the DLL.
The same is true for LINQ efficiency, where entity classes are just filtering through rows of fields.
Use Attribute + reflection to dynamically assign values between two classes