我是 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);
}
}
我需要将 userID 传递给 get() 函数(如果可能),但我不知道该怎么做。我试图对此进行一些研究,但我什至不知道这种定义类的方式叫什么。我来自 objective-c ,那里的事情看起来更直接。
最佳答案
I do not even know what this way of defining a class is called
这是一个泛型类。
public class SimpleGetter<TSubs> : GetterBase<TSubs>, ISubscriptionsSingleGetter<TSubs>
where TSubs : class, ISimpleSubscription, new()
它有一个泛型类型参数 TSubs
.这个类继承了 GetterBase<TSubs>
并实现接口(interface) 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>();
创建上述实例后,您可以调用 Get
方法为 Tewr , 在他的评论中指出:
var response = ((ISubscriptionsSingleGetter<FakeSubs>)simpleGetter).Get(42);
关于C# public class where T : class, Class, new() 混淆,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36998370/