开发者

ambiguous/conflicting constructors in generic class

I've got a generic class:

public class BaseFieldValue<T>
{
    public BaseFieldValue()
    {
        //...
    }

    public BaseFieldValue(string value)
    {
        //...
    }

    public BaseFieldValue(T value)
    {
        //...
    }
}

Fine. Except...

var myValue = new BaseFieldValue<string>("hello");

Oo开发者_如何转开发ps. The undesired constructor is called. There's a number of ways to address the problem. What's the best solution?


I would probably make one of the overloads into a factory method:

public static BaseFieldValue<T> Parse(string value){}


You could do the following:

public class BaseFieldValue<T>
{
    public struct Special
    {
        internal string m_value;
        public Special(string value)
        {
            m_value = value;
        }
    }

    public BaseFieldValue()
    {
        //...
    }

    public BaseFieldValue(Special value)
    {
        //...
    }

    public BaseFieldValue(T value)
    {
        //...
    }
}

... or, you could add an extra ignored boolean parameter to your special constructor, just to disambiguate it.


Couldn't make Type Contraints do what I wanted, so my workaround is removing the ambiguous constructor while retaining the special case for string:

public class BaseFieldValue<T>
{
    public BaseFieldValue()
    {
        //...
    } 

    public BaseFieldValue(T value) 
    {
        //however many things you need to test for here
        if (typeof(T) == typeof(string))
        {
            SpecialBaseFieldValue(value.ToString());
        }
        else
        {
            //everything else
        }
        //...
    }

    private void SpecialBaseFieldValue(string value)
    {
        //...
    }

}


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

public class BaseFieldValue<T>
{
    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<string>("hello");

// call the string constructor
var myValue = new BaseFieldValue<int>("hello");


May be you can try thi:

var myValue = new BaseFieldValue<Object>("hello" as Object);  
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜