【问题标题】:VB.NET cross compatibility with C#VB.NET 与 C# 的交叉兼容性
【发布时间】:2011-02-23 18:22:20
【问题描述】:

我有一个带有通用接口的 C# 项目

public interface IMyFoo<T> { void DoSomething(T instance); }

我还有一个 C# 项目,其接口继承自多个 IMyFoos

public interface IMyBar : IMyFoo<Type1>, IMyFoo<Type2> { ... }

在 C# 领域一切正常(包括以下在 VB 中不起作用的场景)。

我有一个引用此 C# 库的 VB .NET 项目。

我有一个 IMyBar 的实例并尝试如下使用:

Dim instance as MyType1 = ...
Dim bar as IMyBar = ...
bar.DoSomething(instance) ' This generates a compile error: 
' 'DoSomething' is ambiguous across the inherited interfaces 'IMyFoo(Of MyType1)' and 'IMyFoo(Of MyType2)'. 

怎么了?我可以像这样 DirectCast 并且效果很好……但我真的不想这样做

DirectCast(bar, IMyFoo(Of MyType1)).DoSomething(instance)

【问题讨论】:

  • MyType1 和 Type1 和 Type2 之间的关系有点不明显。
  • gaearon:MyType1 和 MyType2 只是 C# 项目中定义的不相关的具体类。

标签: c# .net vb.net interop


【解决方案1】:

你可能不得不cast:

与仅从单一基类型派生的其他类型不同,一个接口可以派生自多个基接口。因此,接口可以从不同的基接口继承同名类型成员。在这种情况下,多重继承的名称在派生接口中不可用,并且通过派生接口引用这些类型成员中的任何一个都会导致编译时错误,无论签名或重载如何。相反,必须通过基本接口名称来引用冲突的类型成员。

【讨论】:

  • 感谢您的参考。对于微软来说,这确实是一个非常糟糕的借口,我希望这不是微软半生不熟的实施的另一个无法解决的遗物。你引用的那篇文章的日期是 2003 年……7 年后,我希望他们能解决这个问题?
  • 我认为您不会很快看到这个问题得到解决。这是2010版本。 msdn.microsoft.com/en-us/library/x1wz55xc.aspx
  • Chris 是正确的,它不是固定的,我相信这一切都是在 office interop 中首次曝光的
  • @Microsoft:如果有人在读这篇文章:从字面上看,如果我整天制作这些半生不熟的解决方案,我会感到羞耻。
【解决方案2】:

只是为了进一步详细说明,VB 不直接支持您正在做的事情的原因是因为您展示的只是一个使用相同方法实现两个接口的类的特例。每当 VB 看到这一点时,它都会强制强制转换以明确您打算使用哪个。 VB 设计者认为这将使代码不易出错。 C# 更进一步,假设您知道自己在做什么,并允许您进行调用。您可以通过使用具有相同方法的两个接口的更通用情况来使 C# 获得相同的基本错误:

public interface IMyFoo1 { void DoSomething(string instance); }
public interface IMyFoo2 { void DoSomething(string instance); }
public interface IMyBar : IMyFoo1, IMyFoo2 { }
public class MyTestClass : IMyBar
{
    //Explicit interface declaration required
    void IMyFoo1.DoSomething(string instance) { }
    void IMyFoo2.DoSomething(string instance) { }
}

string s = "";
IMyBar bar = new MyTestClass();
bar.DoSomething(s);//The call is ambiguous between the following methods or properties...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-11-29
    • 2017-04-19
    • 2011-10-12
    • 2016-11-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多