在C#中键入非泛型接口泛型成员实现的约束

Tam*_*ege 8 c# generics interface

假设我有一个这样的界面:

interface IAwesome
{
    T DoSomething<T>();
}
Run Code Online (Sandbox Code Playgroud)

有没有办法用类型约束实现DoSomething方法?显然,这不起作用:

class IncrediblyAwesome<T> : IAwesome where T : PonyFactoryFactoryFacade
{
    public T DoSomething()
    {
        throw new NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)

这显然是行不通的,因为这个DoSomething()不能完全满足IAwesome的合同 - 它只适用于类型参数T的所有可能值的子集.有没有办法使这个工作缺少一些"铸造"黑魔法"(如果答案是否定的话,这就是我最后要做的事情)?

老实说,我不认为这是可能的,但我想知道你们的想法.

编辑:有问题的接口是System.Linq.IQueryProvider所以我无法修改接口本身.

Luc*_*ero 7

不,这在设计上是行不通的,因为这意味着合同IAwesome不会(完全)满足.

只要IncrediblyAwesome<T>实现IAwesome,一个允许这样做:

IAwesome x = new IncrediblyAwesome<Something>()
Run Code Online (Sandbox Code Playgroud)

显然,使用您的附加约束,这可能无法工作,因为用户IAwesome无法知道对其施加的限制.

在您的情况下,我能想到的唯一解决方案是(进行运行时检查):

interface IAwesome { // assuming the same interface as in your sample
    T DoSomething<T>();
}

class IncrediblyAwesome<TPony> : IAwesome where TPony : PonyFactoryFactoryFacade {
    IAwesome.DoSomething<TAnything>() {
        return (TAnything)((object)DoSomething()); // or another conversion, maybe using the Convert class
    }

    public TPony DoSomething() {
        throw new NotImplementedException();
    }
}
Run Code Online (Sandbox Code Playgroud)