Creating a wrapper for TreeView.Node
Lets say I have the following code:
public class Base
{
// Some stuff here
public int var
}
public class UsingBase
{
// Some more stuff here
public Base B = new Base();
}
Now let's say the actual code of these classes is huge and I would like UsingBase to do some extra stuff. So I'm thinking about subclassing it. Now let's say that what I really want to do is add a method that gives me two times var. Since var is a field of Base, it would be more elegant to add the method to a subclass of Base, and not to a subclass of UsingBase. But I don't want to rewrite UsingBase, and UsingBase uses Base and not my subclass of Base. Actually, this is exactly what I want to do:
TreeView (.NET) has a property of type TreeNodeCollection called Nodes that stores a bunch of objects of type TreeNode. Each TreeNode in Nodes can have a Tag that I can use to store any object I want. But the class TreeNodeCollection doesn't have 开发者_高级运维a function that gives me the TreeNode that correspond to a certain Tag. So I want to be able to do this:
TreeView myTreeView = new TreeView();
// Add some TreeNode's and asign unique tags to each of them
TreeNode someNode = myTreeView.Nodes.GetNodeByTag(object Tag);
I know I can subclass TreeView and add a function that does that, but I just like the other solution a lot better. So I'm wondering if that's possible.
Since TreeNodeCollection implements IEnumerable, you can just use a LINQ where clause to find nodes by particular tags.
i.e. :
TreeNode myTaggedNode = myTreeView.Nodes.Cast<TreeNode>().Where(n=>n.Tag == myTag).SingleOrDefault()
I'd personally avoid subclassing in this context.
EDIT: Based on your comment; you're wondering whether you can get your treeview to use your subclassed version of TreeNodeCollection that contains the GetNodeByTag(object tag)
method. There's two ways to do this (both of which are going to be overkill solutions compared to the one I presented originally)
Method 1) Subclass TreeNodeCollection and include your GetNodeByTag(object tag)
method. Then subclass TreeView to use your derived TreeNodeCollection
This won't work, since the Nodes property on TreeView isn't virtual
Method 2) Use an extension method on TreeNodeCollection that wraps the linq expression I showed you originally:
public static TreeNodeCollectionExtensions
{
public static TreeNode GetNodeByTag(this TreeNodeCollection tnc, object tag)
{
return tnc.Cast<TreeNode>().Where(n=>n.Tag == tag).SingleOrDefault();
}
}
But again, this is simply wrapping the original linq expression I provided originally.
If you were writing the classes yourself, then yeah, but as you're not, then not exactly.
On the other hand, what you could do is write an extension method for TreeNodeCollection, which would give you the exact same syntax for your call to GetNodeByTag.
精彩评论