User-defined conversion operator from base class

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

    How about:

    public class Entity {...}
    
    public class Body : Entity
    {
      public Body(Entity sourceEntity) { this.Pointer = sourceEntity.Pointer; }
    }
    

    so in code you don't have to write:

    Body someBody = new Body(previouslyUnknownEntity.Pointer);
    

    but you can use

    Body someBody = new Body(previouslyUnknownEntity);
    

    instead.

    It's just a cosmetic change, I know, but it is pretty clear and you can change the internals easily. It's also used in a wrapper pattern that I can't remember a name of (for slightly diff. purposes).
    It's also clear you are creating a new entity from a provided one so should not be confusing as an operator/conversion would be.

    Note: haven't used a compiler so possibility of a typo is there.

提交回复
热议问题