ambiguous/conflicting constructors in generic class

前端 未结 5 1065
小鲜肉
小鲜肉 2021-01-07 01:54

I\'ve got a generic class:

public class BaseFieldValue
{
    public BaseFieldValue()
    {
        //...
    }

    public BaseFieldValue(string val         


        
5条回答
  •  情书的邮戳
    2021-01-07 02:38

    A nasty hack, but probably no worse than any of the alternatives:

    public class BaseFieldValue
    {
        public BaseFieldValue()
        {
            // ...
        }
    
        public BaseFieldValue(StringWrapper value)
        {
            // ...
        }
    
        public BaseFieldValue(T value)
        {
            // ...
        }
    
        public class StringWrapper
        {
            private string _value;
    
            public static implicit operator string(StringWrapper sw)
            {
                return sw._value;
            }
    
            public static implicit operator StringWrapper(string s)
            {
                return new StringWrapper { _value = s };
            }
        }
    }
    

    And now it can be used as you need:

    // call the generic constructor
    var myValue = new BaseFieldValue("hello");
    
    // call the string constructor
    var myValue = new BaseFieldValue("hello");
    

提交回复
热议问题