简体   繁体   English

C#泛型扩展方法的专业化

[英]C# specialization of generic extension methods

I have the following extension methods for my MessageBus : 我的MessageBus有以下扩展方法:

public static class MessageBusMixins
{
    public static IDisposable Subscribe<T>(
        this IObservable<T> observable,
        MessageBus bus)
    where T:class
    {
        ...
    }

    public static IDisposable Subscribe<T>( 
        this IObservable<Maybe<T>> observable,
        MessageBus bus)
    {
        ...
    }
}

which compiles fine. 编译好。 However when I try to use it: 但是,当我尝试使用它时:

IObservable<Maybe<string>> source = ...;
MessageBus bus = ...;

source.Subscribe(bus);

I get the error that neither of the two candidate methods are most specific. 我得到的错误是两种候选方法都不是最具体的。 However I thought that Maybe<T> would be more specific than T or is that not correct? 但是我认为Maybe<T>会比T 具体,还是不正确?

EDIT 编辑

It gets curiouser because if I call the extension method explicitly then: 它变得很糟糕,因为如果我明确地调用扩展方法,那么:

MessageBus.SubscribeTo(source, bus);

Then it works and picks the correct method. 然后它工作并选择正确的方法。

Well, you can fix it by specifying the type argument: 好吧,您可以通过指定type参数来修复它:

source.Subscribe<string>(bus);

... as that's now only the second method is applicable. ......因为现在只有第二种方法适用。

Otherwise, the compiler could call either of: 否则,编译器可以调用以下任何一个:

source.Subscribe<string>(bus);
source.Subscribe<Maybe<string>>(bus);

If you think the first is more specific than the second, you'll have to find the rule in the C# specification which says so :) It's not an unreasonable expectation, but I don't think the normal "more specific" conversions apply to type parameters as well as regular parameters. 如果您认为第一个比第二个更具体,那么您必须在C#规范中找到规则,这样说:)这不是一个不合理的期望,但我不认为正常的“更具体”的转换适用于类型参数以及常规参数。

So for example, in section 7.5.3.2 of the C# 4 spec ("Better Function Member") there a rule about: 例如,在C#4规范的第7.5.3.2节(“更好的功能成员”)中,有一条规则:

  • Otherwise if M P has more specific parameter types than M Q , then M P is better than M Q . 否则,如果M P具有比M Q更多的特定参数类型,则M P优于M Q. [... lots of details about less/more specific ...] [...关于更少/更具体的许多细节...]

... but there's no similar point about type parameters. ...但是关于类型参数没有类似的观点。 (The second about normal parameters talks about type arguments, but that's within the parameter types themselves.) (关于正常参数的第二个讨论类型参数,但这是参数类型本身。)

Another alternative is to simply give the methods different names. 另一种方法是简单地给方法赋予不同的名称。 Do they have subtly different behaviour? 他们的行为有微妙的不同吗? If so, why not make that really obvious via the naming? 如果是这样,为什么不通过命名使这一点变得非常明显? You really don't want someone to get the wrong behaviour just because they were surprised about which overload was called. 你真的不希望别人得到错误的行为只是因为他们对调用哪个重载感到惊讶。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM