下面是我代码的相关部分。在MyTreeView
类(下面的最后一个代码块)中,代码行TncExtensions.TncNodeAdd(this, myTreeViewNode);
生成错误CS7036 There is no argument given that corresponds to the required formal parameter 'myTreeViewNode' of 'TncExtensions.TncNodeAdd(TreeNodeCollection, MyTreeView_Abstract, MyTreeViewNode_Abstract)'
为什么编译器无法弄清楚我的TreeNodeCollection扩展方法的第二个形式参数是什么?
public static class TncExtensions
{
public static int TncNodeAdd(this TreeNodeCollection nodes, MyTreeView_Abstract myTreeView, MyTreeViewNode_Abstract myTreeViewNode)
{
return myTreeView.Nodes.Add(myTreeViewNode);
}
}
public abstract class MyTreeViewNode_Abstract : TreeNode
{
public MyTreeViewNode_Abstract(string text) : base(text)
{
}
}
public class MyTreeViewNode : MyTreeViewNode_Abstract
{
public MyTreeViewNode(string text) : base(text)
{
}
}
public abstract class MyTreeView_Abstract : TreeView
{
}
public class MyTreeView : MyTreeView_Abstract
{
public void CreateTree()
{
MyTreeViewNode myTreeViewNode = new MyTreeViewNode("node text");
TncExtensions.TncNodeAdd(this, myTreeViewNode);
}
}
答案 0 :(得分:1)
我相信您创建的扩展方法没什么用,但是如果您想知道问题出在哪里,那么您使用的扩展方法是错误的。您像访问静态方法一样访问它,以这种方式,您需要根据方法的签名传递3个参数:
TncExtensions.TncNodeAdd(Nodes, this, myTreeViewNode);
或者像扩展方法一样使用它:
this.Nodes.TncNodeAdd(this, myTreeViewNode);
我建议您将扩展方法更改为:
public static int TncNodeAdd(this TreeNodeCollection nodes, MyTreeViewNode_Abstract myTreeViewNode)
{
return nodes.Add(myTreeViewNode);
}
答案 1 :(得分:1)
Reza'a答案仍然是答案,但是为了使我的treenode Add
扩展方法有用,我不得不修改对其的调用。我忘记了添加树节点的过程,您需要指定要将新节点附加到的节点集合。
注意:有关所涉及的基本类,请参阅原始问题中的代码
Reza建议的修改后的添加扩展方式
namespace TreeNodeCollectionExtensions
{
public static class TncExtensions
{
public static int Add(this TreeNodeCollection nodes, DRT.DRT_TvwNode_Abstract myTreeViewNode)
{
int newNodeIndex = nodes.Add(myTreeViewNode);
//Do stuff to custom properties that are members of DRT_TvwNode_Abstract and classes derived from DRT_TvwNode_Abstract
return newNodeIndex;
}
}
}
以这种方式使用
using TreeNodeCollectionExtensions;
public class MyTreeView : MyTreeView_Abstract
{
public MyTreeView() : base()
{
}
public void CreateTree()
{
MyTreeViewNode myTreeViewNode;
//Add node to root of TreeView
//Using named parameter to force the compiler to
//use the Add extension method and not the base Add method
myTreeViewNode = new MyTreeViewNode("root node text");
Nodes.Add(myTreeViewNode: myTreeViewNode);
//Add node one level below root node of TreeView
//Using named parameter to force the compiler to
//use the Add extension method and not the base Add method
myTreeViewNode = new MyTreeViewNode("level 1 node text");
int newLevel1NodeIndex = Nodes[0].Nodes.Add(myTreeViewNode: myTreeViewNode);
//Add node one level below level 1 node just created
//Using named parameter to force the compiler to
//use the Add extension method and not the base Add method
myTreeViewNode = new MyTreeViewNode("level 2 node text");
int newLevel2NodeIndex = Nodes[0].Nodes[newLevel1NodeIndex].Nodes.Add(myTreeViewNode: myTreeViewNode);
//etc., etc.
}
}