User-defined conversion operator from base class

前端 未结 11 1560
南旧
南旧 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:05

    It's not a design flaw. Here's why:

    Entity entity = new Body();
    Body body = (Body) entity;
    

    If you were allowed to write your own user-defined conversion here, there would be two valid conversions: an attempt to just do a normal cast (which is a reference conversion, preserving identity) and your user-defined conversion.

    Which should be used? Would you really want is so that these would do different things?

    // Reference conversion: preserves identity
    Object entity = new Body();
    Body body = (Body) entity;
    
    // User-defined conversion: creates new instance
    Entity entity = new Body();
    Body body = (Body) entity;
    

    Yuk! That way madness lies, IMO. Don't forget that the compiler decides this at compile-time, based only on the compile-time types of the expressions involved.

    Personally I'd go with solution C - and possibly even make it a virtual method. That way Body could override it to just return this, if you want it to be identity preserving where possible but creating a new object where necessary.

提交回复
热议问题