开发者

Conversion fails although generic params are constrainted

Here I got a small example which causes the compliler to deliver a error of type:

"Cannot implicitly convert type 'ProvideValueOne' to 'ValueProviderType'".

In my opinion it is not possible to violate the types in any way, so why is this code not accepted?

enlightenment appreciated.

public interface IProvideValue
{
    int Value { get; }
}

public class ProvideValueOne : IProvideValue
{
    public int Value
    {
        get { return 1; }
    }
}

public class ProvideValueTwo : IProvideValue
{
    public int Value
    {
        get { return 2; }
    }
}

public class BaseEntity<ValueProviderType> where ValueProviderType : IProvideValue
{
    public ValueProviderType Provider
  开发者_如何学Python  {
        get{
            return new ProvideValueOne(); // doesnt´t compile
        }
    }
}


In my opinion it is not possible to violate the types in any way

Oh but it is:

var x = new BaseEntity<ProviderValueTwo>();
ProviderValueTwo y = x.Provider;

So C# is correct to flag this. Did you perchance mean the following?

public class BaseEntity<ValueProviderType>
    where ValueProviderType : IProvideValue, new()
{
    public ValueProviderType Provider
    {
        get{
            return new ValueProviderType();
        }
    }
}

Notice the added new constraint.


The BaseEntity class only expects the ValueProviderType to implement IProvideValue. It has no idea what class it is... if it is even a class (maybe it's a struct??).

What if you add a 'new()' constraint and instantiate an instance of 'ValueProviderType'?

    public class BaseEntity<ValueProviderType> where ValueProviderType : IProvideValue,new()
{
    public ValueProviderType Provider
    {
        get{
            return new ValueProviderType(); // doesnt´t compile
        }
    }
}
0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜