User-defined conversion operator from base class

前端 未结 11 1574
南旧
南旧 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条回答
  •  旧时难觅i
    2020-12-01 03:21

    Honestly, I think the original request is being misunderstood.

    Consider the simple situation where a base class is just serving as a grouping of related classes.

    Ex:

    class Parent ...
    class Child1 : Parent ...
    class Child2 : Parent ...
    

    Where the programmer knows how to explicitly convert from one child class to another.

    The Parent class can be used, for example, in:

    Dictionary
    

    What I think the original request is asking for is:

    How to be able to code:

    Class1 v1 = ...
    Class2 v2 = ...
    
    v1 = v2;
    

    Where inside Parent there is explicit code to do the conversion from Class2 to Class1 objects.

    I have this exact situation in my code.

    The best I managed to do was to add a property to Parent class that knows how to do the conversion and returns the proper typed object.

    This forces me to write my code:

    v1 = v2.AsClass1;

    Where the property AsClass1 in Parent knows how to do the actual conversion from Class2 to Class1.

    Honestly this is a code kludge (its ugly; detracts from from simplicity, can make expressions ridiculously long, obfuscates, and most annoyingly it lacks elegance) but its the best I could come up with.

    And, yes, you guessed it, the Parent class also includes the AsClass2 method :-)

    All I wanted to do was:

    v1 = v2;
    

    and have the compiler silently invoke the method I specified to do the conversion.

    I really don't understand why the compiler does support this :-(

    In my mind this is really no different then:

    int v1;
    decimal v2;
    . . .
    v1 = (int)v2;
    

    The compiler knows to silently invoke some built-in conversion method.

提交回复
热议问题