TL;DR
我希望这段代码能够在C#中编译通过:
public void some_method< T >() where T : class1, class2
是否可能?
完整内容
我有两个方法,除了一个参数以外完全相同。
public SignInResponseMessage Generate(SignInRequestMessage request, (X509Certificate2 || WindowsPrincipal) principal, Uri requestUri)
{
SignInResponseMessage response = null;
ClaimsIdentity identity = null;
if (principal != null)
{
identity = CreateSubject(principal);
response = Generate(request, requestUri, identity);
}
else
{
throw new ArgumentNullException("principal");
}
return response;
}
我目前正在复制这种方法,但它让我有点难以接受,因为我真的想让它更加DRY。看了一下这份文档,似乎很有前途,但它只允许我添加单个类约束。在第二个类上我会得到以下错误:
Error 1 The class type constraint 'class2' must come before any other constraints
如果WindowsPrincipal
和X509Certificate2
是我编写的两个类,我可以轻松地让它们实现相同的接口,然后就完成了,但这不是一个选项。
是否有任何方法可以完成我想做的事情?
如果没有,我想更多地了解使这种操作不可能的基本机制。
where T : class1, interface2
或where T : class, interface1, interface2
。然后通过巧妙地设置接口,你可以接近你想要的东西。 - S. Rojak