Using a common interface several times in the same class

I have an interface

interface IInterface<E>{ E Foo(); } 

Then create a class like this

 class Bar : IInterface<String>, IInterface<Int32> { } 

This works really well, except that I need to define one of two functions with an explicit interface, for example:

 class Bar : IInterface<String>, IInterface<Int32> { String Foo(); Int32 IInterface<Int32>.Foo(); } 

The downside is that I have to do the cast every time I want to reach Foo (), which has an explicit interface.

What are the best ways to deal with this?

I am running a performance dependent application, so I really don't want to make a million throws per second. Is this something that the JIT will define, or should I store the cast version of the instance by itself?

I have not tried this specific code, but it is terribly close to what I am doing.

+6
source share
1 answer

You cannot override by return type, but if you want to avoid casting, you can turn your return type into an out parameter:

 interface IInterface<E> { void Foo(out E result); } class Bar : IInterface<string>, IInterface<int> { public void Foo(out string result) { result = "x"; } public void Foo(out int result) { result = 0; } } static void Main(string[] args) { Bar b = new Bar(); int i; b.Foo(out i); string s; b.Foo(out s); } 
+11
source

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


All Articles