我是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()函数(如果可能的话),但我对如何做到这一点很困惑。我试图对此进行一些研究,但我甚至不知道这种定义类的方式是什么。我来自客观c,事情似乎更直接。
答案 0 :(得分:6)
我甚至不知道这种定义类的方式叫做
这是一个通用类。
public class SimpleGetter<TSubs> : GetterBase<TSubs>, ISubscriptionsSingleGetter<TSubs>
where TSubs : class, ISimpleSubscription, new()
有一个泛型类型参数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>();
创建了上述实例后,您可以将Get
方法称为Tewr,在他的评论中指出:
var response = ((ISubscriptionsSingleGetter<FakeSubs>)simpleGetter).Get(42);
答案 1 :(得分:6)
为了补充Christos的答案并帮助您更好地理解语法,让我们按术语打破课程定义。
public
- 所有来电者都可以看到。
SimpleGetter<TSubs>
- 类名为SimpleGetter,相对于参数TSubs为generic。
: GetterBase<TSubs>
- 它继承自基类,该基类本身就参数TSubs是通用的。
, ISubscriptionsSingleGetter<TSubs>
- 它还实现了通用接口ISubscriptionSingleGetter。
where TSubs:
- 泛型参数TSubs必须属于类型constraints。
class
- 它本身也必须是引用类型。
ISimpleSubscription
- 它必须实现此(非通用)接口。
new()
- 它必须有一个公共无参数构造函数。