简体   繁体   English

C#:泛型—推断泛型的泛型

[英]C#: Generics — Infer the Generic Type of a Generic Type

I don't even know how to ask this question so I'll just give the code example. 我什至不知道如何问这个问题,所以我只给出代码示例。

Here is the domain: 这是域:

public interface ISubscriptionProvider<T>
{
    void Subscribe(Action<T> callback);
}

public class Notification {}

public class CurrentUserNotifications : ISubscriptionProvider<Notification>
{
    public void Subscribe(Action<Notification> callback) { }
}

Here is the method I want to make magical: 这是我要神奇的方法:

public void Subscribe<P, T>(Action<T> callback) where P : ISubscriptionProvider<T>
{
    // body left out -- code uses P
}

This works, and here is how you call it: 这有效,这是您的称呼方式:

Subscribe<CurrentUserNotifications, Notification>((n) => Console.WriteLine(n));

So the question is: Is there any way to make it callable like this : 所以问题是: 有没有办法使它像这样可调用

Subscribe<CurrentUserNotifications>((n) => Console.WriteLine(n));

Basically, can it infer that the action type should be just from the ISubscriptionProvider<T> . 基本上,可以推断出操作类型应该只是来自ISubscriptionProvider<T>

This subscribe method lives on a static class (its a static method, I left that part out). 此订阅方法位于静态类上(它是静态方法,我省略了那一部分)。 The idea is that it will take care of constructing the ISubscriptionProvider<T> and keeping it a singleton (probably with structuremap). 这个想法是,它将负责构造ISubscriptionProvider<T>并将其保持为单例(可能与structuremap一起使用)。 So in use: 因此在使用中:

Messages.Subscribe<CurrentUserNotifications>((n) => Console.WriteLine(n));

Thanks! 谢谢!

Update: 更新:

This is kinda off topic, but if any scala people read this ... 这有点题外话,但是如果有斯卡拉人读过这个……

... is be an example of a higher kinded type? ...是更高种类的例子吗? Something like: 就像是:

public void Subscribe<P<T>>(Action<T> callback) { }

Where P<_> is the higher kinded type? 其中P<_>是较高种类的类型?

Why can't you just use 你为什么不能只用

public void Subscribe<T>(Action<T> callback)
{
}

The type P Parameter is irrelevant in your scenario as it is never used. 在您的方案中,类型P参数无关紧要,因为它从未使用过。

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

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