Type C connection type with interfaces

I really like data structures, and I worked on a class library that implements different types of graphs in different ways. One of the stumbling blocks that I had is to easily combine the specific functions of different types of graphs.

To clarify, let's say I have an interface named IGraph <T>, where T is the data that is stored in each node. Now I also want to have interfaces for IUndirectedGraph <T>, IDigraph <T>, and IWeightedGraph <T, E>, where E is the type used as the weight.

I would like to provide various implementations of the same types of graphs. For example, I would like to provide a class that uses an adjacency list and a class that uses an adjacency matrix. Classes can have slightly different implementations of certain algorithms. As a simple example, the definition of the neighbors of a given object will be different in each implementation.

So, let's say I have these two class declarations:

class WeightedAdjacencyListGraph<T,E> : IUndirectedGraph<T>, IWeightedGraph<T,E>

class WeightedAdjacencyMatrixGraph<T,E> : IUndirectedGraph<T>, IWeightedGraph<T,E>

I would like to be able to declare a type of variable that can store objects of both of these classes, but retaining the functionality defined in all interfaces. Basically, I want to be able to declare a variable type, for example:

<IUndirectedGraph<object>+IWeightedGraph<object,double>> MyGraph = new WeightedAdjacencyListGraph<object,double>();
MyGraph = new WeightedAdjacencyMatrixGraph<object,double>();

, #, ? ? , , , ?

: / ( IWeightedGraph < T, E > ) . , ( ). , / , .

+3
4

, , , , , :

public interface IUndirectedAndWeightedGraph<T,E> :
    IUndirectedGraph<T>, IWeightedGraph<T,E>
{
}

, , , , IUndirectedAndWeighted IUndirected ..

#. , , "" , ( ) , . , , dynamic, - , .

+4

, :

void ProcessGraph<TGraph>(TGraph graph)
    where TGraph: IUndirectedGraph<T>, IWeightedGraph<T,E>
{
}

, .

, . , " " , , , . , , ( ) .

+2

, , , . , :

IComboGraph<T, E> : IUndirectedGraph<T>, IWeightedGraph<T,E>

class WeightedAdjacencyListGraph<T,E> : IComboGraph<T, E>

class WeightedAdjacencyMatrixGraph<T,E> : IComboGraph<T, E>

:

IComboGraph<object, double> MyGraph = new WeightedAdjacencyListGraph<object,double>();
MyGraph = new WeightedAdjacencyMatrixGraph<object,double>();

EDIT: , - , .

+1

, , , .

  • - , , , .

  • In C # 4.0 you can use dynamic. It costs a bit of strong static typing and probably some performance - I will try to avoid this too.

  • Whenever possible, you can use only specific types or var, to simplify making changes through closer communication.

  • You can also write a shell that implements all the interfaces and sends calls to the wrapped instance yourself - also unpleasant.

0
source

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


All Articles