User interface conversion

I just ran into the problem of "custom conversions to or from an interface that are not allowed" in C #. What I was trying to do was create a generic Graph class that could be repeated in several ways, depending on the supported interface. So:

public class Graph<T> : IBreadthFirstSearchTree<T>, IDepthFirstSearchTree<T> { // unnecessary details public static explicit operator IBreadthFirstSearchTree<T>(Graph<T> g) { g.enumerator = new GraphEnumerator<T>(g, SortStrategy.BreadthFirst); return g as IBreadthFirstSearchTree<T>; } public static explicit operator IDepthFirstSearchTree<T>(Graph<T> g) { g.enumerator = new GraphEnumerator<T>(g, SortStrategy.DepthFirst); return g as IDepthFirstSearchTree<T>; } } 

was intended for this use:

 foreach (GraphNode<T> gn in myGraph as IDepthFirstSearchTree) { // do stuff with gn } 

Does anyone know how I can achieve the same syntax results within language restrictions?

+3
c #
Nov 21 '08 at 14:49
source share
1 answer

Just execute your implementations of IDepthFirstSearchTree<T> and IBreadthFirstSearchTree<T> explicit implementations. Thus, members will not be available to directly invoke an expression of type Graph<T> , but using the "like" (or cast), the corresponding members will be available.

I'm not sure that what I really will do is, I would probably completely get rid of the interfaces and have:

 public IEnumerable<T> IterateBreadthFirst() { ... } public IEnumerable<T> IterateDepthFirst() { ... } 
+7
Nov 21 '08 at 14:55
source share



All Articles