Generic method to type casting

前端 未结 8 1134
不思量自难忘°
不思量自难忘° 2021-02-02 11:55

I\'m trying to write generic method to cast types. I want write something like Cast.To(variable) instead of (Type) variable. My wrong versi

8条回答
  •  后悔当初
    2021-02-02 12:27

    You will never get this to work without a 'type converter'(a manual process of mapping across attributes for all known types which simply will not happen). You simply cannot just cast one non-related concrete class to another. It would break the single inheritance model (which is one of the defining principles of modern OOP - read up on 'the Diamond Problem')

    It was also noted about interfaces (polymorphism) - both classes would have to derive from the same interface also (which is along the same lines)

提交回复
热议问题