Generic method to type casting

前端 未结 8 1136
不思量自难忘°
不思量自难忘° 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(dynamic o)
        {
            return (T1) o;
        }
    }
    

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

提交回复
热议问题