具有多个类约束的C#泛型键入 [英] C# generic typing with multiple class constraints

查看:116
本文介绍了具有多个类约束的C#泛型键入的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

TL; DR

我想用C#编译

public void some_method<T>(),其中T:class1,class2

这可能吗?

完整上下文

除了一个参数外,我有两种方法完全相同.

I have two methods that are identical except for one parameter.

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.环顾四周,此文档看起来很有希望,但是它只允许我添加一个类约束.我在第二堂课上遇到了以下错误:

I'm currently replicating this method and it's making me cringe a little inside as I would really like to make this DRY-er. Looking around, this documentation seemed promising, but it only allows me to add a single class constraint. I get the following error on the second class:

错误1类类型约束'class2'必须先于其他约束

Error 1 The class type constraint 'class2' must come before any other constraints

如果 WindowsPrincipal X509Certificate2 是我编写的两个类,则可以轻松地使它们实现相同的接口,我会很高兴,但这不是一个选择.

If WindowsPrincipal and X509Certificate2 were two classes I had written I could easily make them implement the same interface and I would be good to go, but that's not an option.

有什么方法可以完成我想做的事情?

如果没有,我想了解更多有关使这种情况无法实现的潜在机制.

推荐答案

我担心这可能导致在计算实际调用的方法时出现问题.想象一下,如果指定的一个类继承自另一个类,并且该方法有一个替代!!

I am afraid that this could lead to issues with working out what method to actually call. Imagine if one of the classes specified inherited from the other and there was an override for that method!?

请参阅钻石问题"以获取原因的完整说明

如果您要解决它.您可以使用适配器设置公共共享接口,然后使用它.

If you want to work around it. You can set up the common shared interface with an adapter and then use that.

interface IAdaper {
    SomeMethod();
}

class AdapterOne : IAdapter {
    TypeOneToCall  _one;

    public AdapterOne (TypeOneToCall one) {
        _one = one;
    }

    public SomeMethod() {
        return _one.SomeMethod();
    }
}

class AdapterTwo : IAdapter {
    TypeTwoToCall _two;

    public AdapterTwo (TypeTwoToCall two) {
        _two = two;
    }

    public SomeMethod() {
        return _two.SomeMethod();
    }
}

class Generic<T> where T : IAdapter {

    // Your implementation here.
}

这篇关于具有多个类约束的C#泛型键入的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆