gpt4 book ai didi

c# - C# 中具有多个泛型类型的泛型会导致允许和不允许的歧义

转载 作者:太空狗 更新时间:2023-10-29 21:40:23 24 4
gpt4 key购买 nike

我最近写了这个并且很惊讶它编译:

public class MyGeneric<U, V> {
MyGeneric(U u) { ... }
MyGeneric(V v) { ... }
public void Add(U u, V v) { ... }
public void Add(V v, U u) { ... }
}

如果我按如下方式使用此类,我会在调用 Add 时得到“模糊的构造函数引用”和“模糊的调用”。

var myVar = new MyGeneric<int, int>(new MyIntComparer());

显然,当我将 int 和 double 用作泛型类型时,没有歧义,当然,当我同时使用这两个 int 时除外,它们也会同时分配给 double。

var myVar = new MyGeneric<int, double>(new MyIntComparer());
myVar.Add(3, 5);

于是我想到下面的也可以,没想到报错了。为什么下面不允许编译?

public interface IMyInterface<T, S> {
void Add(T t, S s);
}

public class MyGeneric<U, V> : IMyInterface<U, V>, IMyInterface<V, U> {
public MyGeneric(U u) { }
public MyGeneric(V v) { }
void IMyInterface<U, V>.Add(U u, V v) { ... }
void IMyInterface<V, U>.Add(V v, U u) { ... }
}

无论我使用隐式接口(interface)实现还是显式接口(interface)实现,编译器都会声明

'MyGeneric<U,V>' cannot implement both 'IMyInterface<U,V>' and 'IMyInterface<V,U>' because they may unify for some type parameter substitutions

为什么第一个被允许写?

最佳答案

1-为什么不允许编译以下内容?

部分回复在该帖子中:Why does the C# compiler complain that "types may unify" when they derive from different base classes?

C# 4 规范的第 13.4.2 节指出:

The interfaces implemented by a generic type declaration must remain unique for all possible constructed types. Without this rule, it would be impossible to determine the correct method to call for certain constructed types.

2- 为什么第一个被允许写?

编译器在编译时执行泛型类型检查,C# 4 规范的第 7.4.3.5 节指出:

While signatures as declared must be unique, it is possible that substitution of type arguments results in identical signatures. In such cases, the tie-breaking rules of overload resolution above will pick the most specific member. The following examples show overloads that are valid and invalid according to this rule:

interface I1<T> {...}
interface I2<T> {...}
class G1<U>
{
int F1(U u); // Overload resulotion for G<int>.F1
int F1(int i); // will pick non-generic
void F2(I1<U> a); // Valid overload
void F2(I2<U> a);
}
class G2<U,V>
{
void F3(U u, V v); // Valid, but overload resolution for
void F3(V v, U u); // G2<int,int>.F3 will fail
void F4(U u, I1<V> v); // Valid, but overload resolution for
void F4(I1<V> v, U u); // G2<I1<int>,int>.F4 will fail
void F5(U u1, I1<V> v2); // Valid overload
void F5(V v1, U u2);
void F6(ref U u); // valid overload
void F6(out V v);
}

关于c# - C# 中具有多个泛型类型的泛型会导致允许和不允许的歧义,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13718989/

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