gpt4 book ai didi

c# - "no implicit reference conversion"即使定义了转换

转载 作者:行者123 更新时间:2023-11-30 22:55:24 24 4
gpt4 key购买 nike

我编写了以下代码以尝试提供类型安全的接口(interface):

namespace MWE
{
public abstract class C {}
public class A : C {}
public class B : C {}

public class Container<T> where T : C
{
public readonly T Value;

public static implicit operator T(Container<C> c)
{
return c.Value;
}
}

public interface IWrapper<out TC> where TC : C {}

public class Foo
{
public Foo(IWrapper<Container<C>> wrapper) {}
}
}

不幸的是,这无法编译。 Container<C> -wrapper的一部分Foo 的参数构造函数导致编译器产生以下错误:

The type 'MFE.Container<MFE.C>' cannot be used as type parameter 'TC' in the generic type or method 'IWrapper<TC>'. There is no implicit reference conversion from 'MFE.Container<MFE.C>' to 'MFE.C'.
The type 'MFE.Container<MFE.C>' must be convertible to 'WeirdTestStuff.C' in order to use it as parameter 'TC' in the generic interface 'MFE.IWrapper<out TC>'.

我无法弄清楚问题到底出在哪里,因为转换的协方差似乎存在,甚至还有来自 Container<T> 的隐式转换。至 T定义。自 T : C ,我认为它应该像这样工作。

我想保留 Foo的构造函数,如果可能的话。

我希望有人能指出我这个问题的解决方案

最佳答案

even an implicit conversion from a Container to T defined

确实如此,但这不是编译器所要求的。它需要:

implicit reference conversion

(我的重点)

隐式引用转换不是由任何用户定义的运算符提供的,并且仅当一种类型(直接或通过中间类型)派生自另一种类型时才被允许1

Container has-a C 并且可以通过用户定义的运算符转换为 C 但是这还不足以使其成为 C。您的问题太抽象了,无法说明此处的修复方法 - Container 是否应该是非通用的并派生自 C?这是“关闭”编译器的明显方法,但可能无法解决您的实际问题。

您不能使用泛型使类型的基类型在运行时可设置。


1这些是 Eric Lippert 的 Representation-preserving conversions

关于c# - "no implicit reference conversion"即使定义了转换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55276136/

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