Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/295.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/.net/20.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 方法,其返回类型实现多个接口_C#_.net_Inheritance_Interface - Fatal编程技术网

C# 方法,其返回类型实现多个接口

C# 方法,其返回类型实现多个接口,c#,.net,inheritance,interface,C#,.net,Inheritance,Interface,目前我有以下几点: interface IMyInterfaceReturnType : IEnumerable<string>, IDisposable { } interface IMyInterface { IMyInterfaceReturnType MyInterfaceMethod(); } 接口IMyInterfaceReturnType:IEnumerable,IDisposable { } 接口接口 { IMyInterfaceReturnType My

目前我有以下几点:

interface IMyInterfaceReturnType : IEnumerable<string>, IDisposable
{
}

interface IMyInterface
{
    IMyInterfaceReturnType MyInterfaceMethod();
}
接口IMyInterfaceReturnType:IEnumerable,IDisposable
{
}
接口接口
{
IMyInterfaceReturnType MyInterfaceMethod();
}
有没有一种方法可以改变MyInterfaceMethod()的方法签名,这样我就可以表示我将返回一个IEnumerable和一次性的对象,而无需创建中间接口?说:

interface IMyInterface
{
    IEnumerable<string>, IDisposable MyInterfaceMethod();
}
接口IMyInterface
{
IEnumerable,IDisposable MyInterfaceMethod();
}

这可以通过泛型实现:

interface IMyInterface<T> where T :IEnumerable<string>, IDisposable 
{
    T MyInterfaceMethod();
}
接口imy接口,其中T:IEnumerable,IDisposable
{
T MyInterfaceMethod();
}

这将解决什么样的问题?我这样问是因为我试图看到这种事情的必要性。是的,您可以使用泛型来实现这一点,正如已经回答过的,但这到底解决了什么问题?具体来说,不,没有办法说“这将返回任何将实现这些N接口的奇数类型”。您只能说“这将返回这个特定的类型,它碰巧也实现了这N个接口”。我不确定泛型解决方案是否是您所追求的,但是。@LasseV.Karlsen我想返回一个类,该类迭代一个打开的文件(同时封装该逻辑)。提供IEnumerable允许用户遍历行,而IDisposable部分允许调用方在完成后关闭底层文件流。@LasseV.Karlsen我发现奇怪的是,没有办法返回“任何将实现这些N接口的奇怪类型”由于可以创建一个实现任意N个接口()的类/接口,因此方法只能有1个返回类型,而.NET没有“实现N个接口的任何类型”的概念,因此这是不可能的。即使使用泛型语法,从下面的答案来看,您仍然需要确定
T
的一种类型。约束条件是,您可以为
T
指定的唯一合法类型是那些碰巧也实现了这些接口的类型,但是方法的返回类型仍然是单个
T
。这不要求接口调用方指定返回类型吗。我上面的代码不需要调用方指定返回类型。我不确定这会有多大帮助。不确定OP到底想要什么。@LasseV.Karlsen第一个块是合法的。是的,但不幸的是,没有泛型,没有语法来声明您想要的,或者。。。当然,您可以声明自己的接口,该接口暗示了另外两个接口,但我怀疑这是否是您想要的。