Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
362 views
in Technique[技术] by (71.8m points)

c# - What is the correct way to call an extension method (TreeNodeCollection Add method)?

The pertinent parts of my code are below. In the MyTreeView class (last block of code below), the line of code TncExtensions.TncNodeAdd(this, myTreeViewNode); generates the error CS7036 There is no argument given that corresponds to the required formal parameter 'myTreeViewNode' of 'TncExtensions.TncNodeAdd(TreeNodeCollection, MyTreeView_Abstract, MyTreeViewNode_Abstract)'

Why can't the compiler figure out what the 2nd formal parameter is for my TreeNodeCollection extension method?

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);
    }
}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

I believe the extension method which you created is not of much use but if you are curious to know what the problem is, you are using the extension method wrong. You are accessing it like a static method, in this style you need to pass 3 arguments based on the signature of the method:

TncExtensions.TncNodeAdd(Nodes, this, myTreeViewNode);

Or use it like an extension method:

this.Nodes.TncNodeAdd(this, myTreeViewNode);

I suggest you change the extension method to:

public static int TncNodeAdd(this TreeNodeCollection nodes, MyTreeViewNode_Abstract myTreeViewNode)
{
    return nodes.Add(myTreeViewNode);
}

To learn more, take a look at Extension Methods.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...