C#public class其中T:class,Class,new()混淆

pni*_*zle 3 c# inheritance abstract-class class

我是C#的新手,我面对的是一个具有这种结构的类:

public class SimpleGetter<TSubs> : GetterBase<TSubs>, ISubscriptionsSingleGetter<TSubs>
    where TSubs : class, ISimpleSubscription, new()
{
    UserSubscriptionsResponse<TSubs> ISubscriptionsSingleGetter<TSubs>.Get()
    {
        return ((ISubscriptionsSingleGetter<TSubs>)this).Get(null);
    }

    UserSubscriptionsResponse<TSubs> ISubscriptionsSingleGetter<TSubs>.Get(string userId)
    {
        return GetSubsResponse(userId);
    }
}
Run Code Online (Sandbox Code Playgroud)

我需要将userID传递给get()函数(如果可能的话),但我对如何做到这一点很困惑.我试图对此进行一些研究,但我甚至不知道这种定义类的方式是什么.我来自客观c,事情似乎更直接.

Chr*_*tos 6

我甚至不知道这种定义类的方式是什么

这是一个通用类.

  public class SimpleGetter<TSubs> : GetterBase<TSubs>, ISubscriptionsSingleGetter<TSubs>
    where TSubs : class, ISimpleSubscription, new()
Run Code Online (Sandbox Code Playgroud)

它有一个泛型类型参数TSubs.该类继承GetterBase<TSubs>并实现接口ISubscriptionsSingleGetter<TSubs>.此外,TSubs必须是引用类型,并且必须具有无参数构造函数,该构造函数实现ISimpleSubscription接口.

public class FakeSubs : ISimpleSubscription
{
    public FakeSubs()
    {

    }

    // Here you have to implement ISimpleSubscription. 
    // You could also define any properties, methods etc.
}

// Now you could use your generic class as below:

var simpleGetter = new SimpleGetter<FakeSubs>();
Run Code Online (Sandbox Code Playgroud)

创建了上面的实例后,您可以将该Get方法称为Tewr,在他的评论中指出:

var response = ((ISubscriptionsSingleGetter<FakeSubs>)simpleGetter).Get(42);
Run Code Online (Sandbox Code Playgroud)


Rot*_*tem 6

只是为了补充Christos的答案并帮助您更好地理解语法,让我们按术语打破类定义术语.

public - 所有来电者都可以看到.

class- 参考类型(即不是a struct).

SimpleGetter<TSubs>- 类名是SimpleGetter,它对于参数TSubs 是通用的.

: GetterBase<TSubs> - 它继承自基类,该基类本身就参数TSubs是通用的.

, ISubscriptionsSingleGetter<TSubs> - 它还实现了通用接口ISubscriptionSingleGetter.

where TSubs:- 通用参数TSub必须具有的类型有一些约束.

class - 它本身也必须是参考类型.

ISimpleSubscription - 它必须实现这个(非通用)接口.

new() - 它必须有一个公共无参数构造函数.