I just ran into the "user-defined conversions to or from an interface are not allowed" problem in C#. What I was attempting to do was create a generic Graph class that could be iterated over in a couple different 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
}
Anyone know how I can achieve the same syntactic results within the constraints of the language?
Just make your implementations of IDepthFirstSearchTree<T>
and IBreadthFirstSearchTree<T>
explicit implementations. That way the members won't be available to be called directly on an expression of type Graph<T>
, but using "as" (or a cast) the appropriate members will be available.
I'm not sure that's what I'd really do though - I'd probably get rid of the interfaces entirely and have:
public IEnumerable<T> IterateBreadthFirst() { ... }
public IEnumerable<T> IterateDepthFirst() { ... }
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.