User-defined conversion operator from base class

前端 未结 11 1571
南旧
南旧 2020-12-01 02:40

Introduction

I am aware that \"user-defined conversions to or from a base class are not allowed\". MSDN gives, as an explanation to this rule, \"You

11条回答
  •  鱼传尺愫
    2020-12-01 03:15

    Well, when you are casting Entity to Body, you are not really casting one to another, but rather casting the IntPtr to a new entity.

    Why not create an explicit conversion operator from IntPtr?

    public class Entity {
        public IntPtr Pointer;
    
        public Entity(IntPtr pointer) {
            this.Pointer = pointer;
        }
    }
    
    public class Body : Entity {
        Body(IntPtr pointer) : base(pointer) { }
    
        public static explicit operator Body(IntPtr ptr) {
            return new Body(ptr);
        }
    
        public static void Test() {
            Entity e = new Entity(new IntPtr());
            Body body = (Body)e.Pointer;
        }
    }
    

提交回复
热议问题