User-defined conversion operator from base class

前端 未结 11 1556
南旧
南旧 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

    (Invoking necromancy protocols...)

    Here's my use-case:

    class ParseResult
    {
        public static ParseResult Error(string message);
        public static ParseResult Parsed(T value);
    
        public bool IsError { get; }
        public string ErrorMessage { get; }
        public IEnumerable WarningMessages { get; }
    
        public void AddWarning(string message);
    }
    
    class ParseResult : ParseResult
    {
        public static implicit operator ParseResult(ParseResult result); // Fails
        public T Value { get; }
    }
    
    ...
    
    ParseResult ParseSomeBigLongTypeName()
    {
        if (SomethingIsBad)
            return ParseResult.Error("something is bad");
        return ParseResult.Parsed(new SomeBigLongTypeName());
    }
    

    Here Parsed() can infer T from it's parameter, but Error can't, but it can return a typeless ParseResult that is convertible to ParseResult - or it would be if not for this error. The fix is to return and convert from a subtype:

    class ParseResult
    {
        public static ErrorParseResult Error(string message);
        ...
    }
    
    class ErrorParseResult : ParseResult {}
    
    class ParseResult
    {
        public static implicit operator ParseResult(ErrorParseResult result);
        ...
    }
    

    And everything is happy!

提交回复
热议问题