码:

public interface IAssignable
{
    IAssignable AssignMe { get; set; }
}

public class GenericAssignExample<T> where T : IAssignable
{
    private T _assignable;

    public void Valid(T toAssign)
    {
        _assignable.AssignMe = toAssign;
    }

    public void AlsoValid(T toAssign)
    {
        _assignable.AssignMe = toAssign.AssignMe;
    }

    public void AlsoValidAsWell(T toAssign)
    {
        _assignable = toAssign;
    }

    public void Invalid(T toAssign)
    {
        _assignable = toAssign.AssignMe;
    }
}


问题:

在最后的示例方法中,不能为方法_assignable(为T where T is IAssignable)分配值toAssign.AssignMe(其为IAssignable类型),编译器将抛出


  “无法将类型'IAssignable'隐式转换为'T'”。


为什么是这样? TIAssignable,因此可以肯定地将IAssignable的实例分配给它吗?

最佳答案

为什么是这样? T是IAssignable的,因此确定可以将IAssignable的实例分配给它吗?


啊不T不是IAssignable,如果是,则不需要泛型。 T仅实现IAssignable

仅仅因为ButtonTextBox继承自Control(或在虚构的示例中实现IControl)并不意味着您可以将TextBox分配给Button,反之亦然。



public interface IAssignable
{
    IAssignable AssignMe { get; set; }
}

public class A : IAssignable
{
    public IAssignable AssignMe { get; set; }
}

public class B : IAssignable
{
    public IAssignable AssignMe { get; set; }
}

// You will be able to instantiate this class with either A or B and both must be valid
public class GenericAssignExample<T> where T : IAssignable
{
    // here, T refers to either A or B.
    private T _assignable;

    public void Valid(T toAssign)
    {
        // assigning either an A or B to the interface...
        // always valid, both implement it
        _assignable.AssignMe = toAssign;
    }

    public void AlsoValid(T toAssign)
    {
        // assigns interface to interface. Always valid.
        _assignable.AssignMe = toAssign.AssignMe;
    }

    public void AlsoValidAsWell(T toAssign)
    {
        // assigns either an A to an A
        // or a B to a B.
        // both always valid.
        _assignable = toAssign;
    }

    public void Invalid(T toAssign)
    {
        // this tries to assign an interface to either an A or a B
        // always invalid.
        _assignable = toAssign.AssignMe;
    }
}

关于c# - 与泛型的对立/协方差-无法分配给T,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/43978711/

10-12 15:27