ambiguous/conflicting constructors in generic class

前端 未结 5 1014
小鲜肉
小鲜肉 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:22

    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
    {
        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)
        {
            //...
        }
    
    }
    

提交回复
热议问题