C # Interface with a method that returns an implementation of multiple interfaces

When working with interfaces, I often encounter the case when I want to make sure that the return value from a property or method or sometimes a parameter for a method implements TWO or more interfaces without creating a new interface.

My specific instance right now is that I want to indicate that the method will result in IEnumerable<SomeType>, which also supports INotifyCollectionChanged- thus, another object using the interface should not have a type and can access both settings. (I don’t want to use it ReadOnlyObservableCollectionexplicitly because it works well with objects ObservableCollection, but I would also like to leave this option open for future interface executives to use it if they want.)

I think this can only be handled by method parameters, and not return values ​​by providing a method declaration like this:

void SetStringData<T>(T data) where T : IEnumerable<string>, INotifyCollectionChanged

To be clear, I would really like the using class to not be able to specify the type of the return type. Like the following, but obviously the syntax does not work or even makes sense.

(IEnumerable<string>, INotifyCollectionChanged) GetStringData()

Any suggestions on how I can do this? Or, if this is not possible, how can I achieve the same results?

+3
source share
5 answers

There is no good solution, but I think adding a code contract to the interface. However, the caller is required to give the result to the interface he needs.

Sort of:

Contract.Ensures(Contract.Result<object>() is IEnumerable<string>);
Contract.Ensures(Contract.Result<object>() is INotifyCollectionChanged);
+2
source

, , , - dynamic, , :

public dynamic GetStringData()
{

}

IDisposable disposable = GetStringData();
ISomeOtherInterface other = GetStringData();

, . , - .

public IComposite GetStringData()
{

}

IEnumerable<string> enumerable = GetStringData();
+2

(), , . , . .

tuple .

+1

, ?

T GetStringData<T>()

T

0

, ? , Widget IEnumerable INotifyCollectionChanged, Widget. , , , , , INotifiableEnumerable, IEnumerable, INotifyCollectionChanged, , INotifiableEnumerable. , , INotifiableEnumerable, IEnumerable, INotifyCollectionChanged.

0

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


All Articles