C# 使用“using”时无法隐式转换为System.IDisposable
给定如下两个接口:C# 使用“using”时无法隐式转换为System.IDisposable,c#,.net,idisposable,C#,.net,Idisposable,给定如下两个接口: public interface MyInterface1 : IDisposable { void DoSomething(); } public interface MyInterface2 : IDisposable { void DoSomethingElse(); } 。。。还有这样一个实现类: public class MyClass : IMyInterface1, IMyInterface2 { public void DoSome
public interface MyInterface1 : IDisposable
{
void DoSomething();
}
public interface MyInterface2 : IDisposable
{
void DoSomethingElse();
}
。。。还有这样一个实现类:
public class MyClass : IMyInterface1, IMyInterface2
{
public void DoSomething() { Console.WriteLine("I'm doing something..."); }
public void DoSomethingElse() { Console.WriteLine("I'm doing something else..."); }
public void Dispose() { Console.WriteLine("Bye bye!"); }
}
。。。我假设应该编译以下代码段:
class Program
{
public static void Main(string[] args)
{
using (MyInterface1 myInterface = new MyClass()) {
myInterface.DoSomething();
}
}
}
。。。相反,我总是收到以下错误消息:
Error 1 'IMyInterface1': type used in a using statement must be implicitly convertible to 'System.IDisposable'
有什么想法吗?谢谢。您还应该看到关于Dispose不公开的编译器错误
public class MyClass : IMyInterface1, IMyInterface2
{
public void DoSomething() { Console.WriteLine("I'm doing something..."); }
public void DoSomethingElse() { Console.WriteLine("I'm doing something else..."); }
void Dispose() { Console.WriteLine("Bye bye!"); }
}
此类中的Dispose方法无法实现IDisposable,因此必须进行更多操作。工作正常
public interface IMyInterface1 : IDisposable
{
void DoSomething();
}
public interface IMyInterface2 : IDisposable
{
void DoSomethingElse();
}
public class MyClass : IMyInterface1, IMyInterface2
{
public void DoSomething() { Console.WriteLine("I'm doing something..."); }
public void DoSomethingElse() { Console.WriteLine("I'm doing something else..."); }
public void Dispose() { Console.WriteLine("Bye bye!"); }
}
class Program
{
public static void Main(string[] args)
{
using (IMyInterface1 myInterface = new MyClass())
{
myInterface.DoSomething();
}
}
}
您只是忘记了将Dispose公开,而接口的名称是错误的MyInterfaceX,而不是IMyInterfaceX
Ideone:您确定键入的所有内容都正确吗?顶部有MyInterface1和MyInterface2,但后面有IMyInterface1和IMyInterface2。@j3d-请仅发布准确的代码。在发布之前验证它。如上所述,我们会得到其他编译错误,而不是您描述的那个。但是,按照您编写上述类型的方式,每个接口类型本身都可以隐式转换为IDisposable。通过实现的不同接口,可以以两种不同的方式将类类型转换为IDisposable,这是您真正的问题吗?@JeppeStigNielsen-不,MyClass只实现一次。这2个分支是折叠的,什么C++调用虚拟继承。他的问题是坏的,但是如果在使用声明中使用var,会发生什么?!@!JeppeStigNielsen它工作正常。@JeppeStigNielsen使用var将所有变体都添加到MyClass的一个或另一个接口。你试过了吗?编辑:嗯,我看你有。也许我会收回我的答案。@JeppeStigNielsen我只有一个编译正确的Visual Studio和一个带输出的ideone。我甚至给了你ideone链接。你需要截图吗?