gpt4 book ai didi

c# - 与泛型的反/协方差 - 不能分配给 T

转载 作者:太空宇宙 更新时间:2023-11-03 12:27:38 25 4
gpt4 key购买 nike

代码:

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,其中 T 是 IAssignable)不能被分配值 toAssign.AssignMe(这是输入 IAssignable), 编译器抛出

"Cannot implicitly convert type 'IAssignable' to 'T'".

这是为什么? TIAssignable 那么确定 IAssignable 的实例可以分配给它吗?

最佳答案

Why is this? T is IAssignable so surely an instance of IAssignable can be assigned to it?

啊,不是吗? 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com