Cross VB.NET Compatibility with C #

I have a C # project with a common interface

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

I also have a C # project with an interface that inherits from several IMyFoos

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

Everything works fine in C # ground (including the script below that doesn't work in VB).

I have a VB.NET project that references this C # library.

I have an instance of IMyBar and am trying to use it as follows:

 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)'. 

What? I can DirectCast like this, and it works fine ... but I REALLY probably don't

 DirectCast(bar, IMyFoo(Of MyType1)).DoSomething(instance) 
+4
source share
2 answers

You probably have to cast :

Unlike other types, which are produced from only one basic type, an interface can be obtained from several basic interfaces. Because of this, an interface can inherit a type element of the same name from different base interfaces . In this case, a multiple inherited name is not available in the derived interface, and accessing any of these type members through the derived interface causes a compile-time error, regardless of signatures or overload. Instead, conflicting type members should be referenced through the name of the underlying interface.

+6
source

To explain in detail, the reason why VB does not directly support what you are doing is what you showed, this is just a special case of a class that implements two interfaces with the same method. Whenever VB sees this, it forces the cast to make it explicit which one you are going to use. VB designers decided that this would make the code less error prone. C # goes further and assumes that you know what you are doing and allows you to make this call. You can make C # get the same basic error using the more general case of two interfaces with the same method:

 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... 
+1
source

Source: https://habr.com/ru/post/1341017/


All Articles