C# Generic Passing different objects with same properties

眉间皱痕 提交于 2019-11-29 15:43:57
Patrick Hofman

You have two options in my opinion.

  1. Implement an interface

    If you create an interface containing all shared properties and methods, you can create one method accepting that interface, or when using generics, all types implementing it. (Yes, it is possible to implement an interface in EF generated classes)

  2. Use dynamic

    The dynamic keyword will give you a lot of freedom. You can pretend if a property or method exists. This is checked at runtime when you pass in the object. You should use dynamic with care, since it can harm your software quality.

The first option is preferred. It is the best solution, but it requires you to have access over the classes. If the classes are in a third party library, dynamic is probably your only solution.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!