简体   繁体   English

方法约束必须是泛型类的超类

[英]Method constraint must be super of class generic

How can I do the following? 我该怎么办?

I have a method which I need to say its generic type must be the super of the classes generic type. 我有一个方法,我需要说它的泛型必须是类的泛型的父类。

Here is an example: 这是一个例子:

class Logger : ILogger, IStartable {}

///use
new FluentBuilder<Logger>().As<ILogger>().As<IStartable>();

This shows my intent, however does not work (as it is not syntactically incorrect): 这显示了我的意图,但是不起作用(因为它在语法上不是错误的):

public class FluentBuilder<TService> where TService : class
{
    public FluentBuilder<TService> As<TContract>() where TService : TContract
    {
        return this;
    }
}

This is not exactlywhat you want, but maybe a step in the correct direction. 这不是您想要的,但可能是朝正确方向迈出的一步。 You can implement your As method as extension method: 您可以将As方法实现为扩展方法:

public static class Ex
{
    public static FluentBuilder<TService> As<TService, TContract>(this FluentBuilder<TService> that) 
        where TContract : class 
        where TService : class, TContract
    {
        return that;
    }
}

The usage syntax is then: 用法语法如下:

new FluentBuilder<Logger>().As<Logger, ILogger>().As<Logger, IStartable>();

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

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