How would you improve this shallow copying class?

后端 未结 4 1980
暗喜
暗喜 2020-12-19 13:20

I\'ve written a class with a single static method that copies property values from one object to another. It doesn\'t care what type each object is, only that they have ide

4条回答
  •  误落风尘
    2020-12-19 14:20

    • Change your type parameter names to comply with naming conventions, e.g. TFrom and TTo, or TSource and TDest (or TDestination).

    • Do most of your work in a generic type instead of in just a generic method. That allows you to cache the properties, as well as allowing type inference. Type inference is important on the "TFrom" parameter, as it will allow anonymous types to be used.

    • You could potentially make it blindingly fast by dynamically generating code to do the property copying and keeping it in a delegate which is valid for the "from" type. Or potentially generate it for every from/to pair, which would mean the actual copying wouldn't need to use reflection at all! (Preparing the code would be a one-time hit per pair of types, but hopefully you wouldn't have too many pairs.)

提交回复
热议问题