Generic method to type casting

前端 未结 8 1118
不思量自难忘°
不思量自难忘° 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:26

    Instance a is an object to the moment of casting to B. Not A type, but object. So, it is impossible to cast object to B because of CLR can not know, that o contains explicit operator.
    EDIT:
    Yeah! Here is solution:

    public class Cast
    {
        public static T1 To<T1>(dynamic o)
        {
            return (T1) o;
        }
    }
    

    Now CLR exactly knows, that o is an instance of type A and can call the explicit operator.

    0 讨论(0)
  • 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)

    0 讨论(0)
提交回复
热议问题