类型参数统一

发布于 2024-08-24 15:28:48 字数 345 浏览 6 评论 0原文

为什么 C# 中不允许这样做? 替代文本 http://img706.imageshack.us/img706/7360/restriction.png< /a>

实际上我希望能够

alias Y<A, B> : X<A, B>, X<B, A>

在这里写下 The unification is 实际上是需要的;如果 A = B 则只需定义一种方法。

Why is this disallowed in C#?
alt text http://img706.imageshack.us/img706/7360/restriction.png

Actually I'd like to be able to write

alias Y<A, B> : X<A, B>, X<B, A>

The unification is actually desired here; if the A = B then just one method should be defined.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

楠木可依 2024-08-31 15:28:48

我想到的第一个原因如下。

class Example : Y<int,int> {
 ...
}

在这种情况下,类型 Y 两次实现相同的接口,但可以具有相同方法的不同实现。这会在编译器中为方法 Tx 在实现和调用方面产生无法解决的歧义。

例如下面的问题。

class OtherExample<A,B> : Y<A,B> {
  B Tx(A x) { 
    Console.WriteLine("Top method in the file");
    return default(B); 
  }
  A Tx(B x) { 
    Console.WriteLine("Bottom method in the file");
    return default(A);
  }
}

如果忽略统一错误,这是 Y 的合法实现。现在想象一下用户执行了以下操作

var v1 = new OtherExample<int,int>();
v1.Tx(42);

在这种情况下到底会发生什么?编译器或 CLR 如何解决歧义?您将拥有具有相同签名的相同名称的方法。

The first reason that comes to mind is the following.

class Example : Y<int,int> {
 ...
}

In this case the type Y implements the same interface twice but can have differing implementations of the same method. This creates an unresolvable ambiguity in the compiler for the method Tx in both implementation and calling.

For example take the following problem.

class OtherExample<A,B> : Y<A,B> {
  B Tx(A x) { 
    Console.WriteLine("Top method in the file");
    return default(B); 
  }
  A Tx(B x) { 
    Console.WriteLine("Bottom method in the file");
    return default(A);
  }
}

If you ignore the unification error this is a legal implementation of Y<A,B>. Now imagine the user did the following

var v1 = new OtherExample<int,int>();
v1.Tx(42);

What exactly would happen in this scenario? How would the compiler, or the CLR for that matter, be able to resolve the ambiguity? You'd have identically named methods with identical signatures.

用心笑 2024-08-31 15:28:48

相反,您可以将类型定义为:

public interface Y<A> : X<A,A>
{
}

Instead could you define your type as:

public interface Y<A> : X<A,A>
{
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文