X 和 Y 的一般约束

Generic constraint of X AND Y

是否可以使用泛型约束对抽象类型派生类型实施约束 class,但仅限于那些实现接口的派生类型?

示例:

abstract class Dependency
{
    public abstract void IMustDoThis();
}

interface IOptionalDependency
{
    void IMightDoThis();
}

sealed class AlmightyDependency : Dependency, IOptionalDependency
{
    // I have sealed this for a reason!

    public override void IMustDoThis()
    {
        // I am almighty because I do this!
    }

    public void IMightDoThis()
    {
        // I am almighty because I can do this too!
    }
}

class ThisIsntTheAnswer : AlmightyDependency
{
    // AlmightyDependency is sealed...this is not the answer I'm looking for!
}

static class DoSomeAlmightyWork
{
    static void INeedToDoBoth<T>(T dependency) where T : Dependency ...AND... IOptionalDependency
    {
        dependency.IMustDoThis();
        if (something)
        {
            dependency.IMightDoThis();
        }
    }
}

有没有办法在 C# 中强制执行这种依赖关系?

当前解决方案:

我目前的解决方案如下:

static void INeedToDoBoth(Dependency dependency, IOptionalDependency optional)
{
    dependency.IMustDoThis();
    if (something)
    {
        optional.IMightDoThis();
    }
}

但这意味着我两次传递相同的参数,看起来很脏!

INeedToDoBoth(dependency, dependency);

我考虑过的另一种解决方法是:

static void INeedToDoBoth(IOptionalDependency optional)
{
    Dependency dependency = optional as Dependency;
    if(dependency != null)
    {
        dependency.IMustDoThis();
        // But if I MUST do this, and I was null...then what?
    }

    if (something)
    {
        optional.IMightDoThis();
    }
}

听起来你只是缺少在约束中将 class 和接口指定为逗号分隔列表的能力:

static void INeedToDoBoth<T>(T dependency)
    where T : Dependency, IOptionalDependency

请注意,class 约束 必须 在此处排在第一位。

有关详细信息,请参阅 MSDN page for type parameter constraints 或 C# 5 规范第 10.1.5 节。