【发布时间】:2018-06-05 22:33:15
【问题描述】:
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-er。环顾四周,this documentation 似乎很有希望,但它只允许我添加一个类约束。我在第二堂课上收到以下错误:
错误 1 类类型约束“class2”必须位于任何其他约束之前
如果 WindowsPrincipal 和 X509Certificate2 是我编写的两个类,我可以轻松地让它们实现相同的接口,我会很高兴,但这不是一个选择。
有什么方法可以完成我想做的事吗?
如果没有,我想了解更多关于使这成为不可能的底层机制。
【问题讨论】:
-
这是不可能的。一个潜在的解决方案是使用适配器模式,您的适配器实现您的接口,然后使用您的接口作为约束。
-
你有适配器模式的好资源吗?这对我来说是一个新的
-
四人帮已经很好地描述了它。您可以使用以下资源:blackwasp.co.uk/Adapter.aspx
-
C# 不允许多重继承,所以不能使用两个类作为类型约束。
-
您可以使用
where T : class1, interface2或where T : class, interface1, interface2。然后通过巧妙地设置你的界面,你可以接近你想要的。
标签: c#