简体   繁体   中英

Passing method as parameter to function

Is there a way of passing in a method to a function as a parameter and then calling it via list.Sort()? I've tried this:

public static string BuildHumanSitemap(Func<TreeNode, TreeNode, int> sortMethod, params string[] classNames)
{
    //calling list sort on method passed as parameter
    nodes.sort(sortMethod);
 }

Where the functions i want to pass in all take the same params eg

private static int SortByDateCreated(TreeNode x, TreeNode y)
{
    DateTime xT = (DateTime)x["DocumentCreatedWhen"];
    DateTime yT = (DateTime)y["DocumentCreatedWhen"];
    return xT.CompareTo(yT);
}

I've also tried using an Action delegate type but the sort method complains when i pass it as a parameter. Can anyone offer a suggestion on how to do this?

Thankyou

创建新的比较委托并将其传递给Sort方法:

nodes.Sort(new Comparison<TreeNode>(sortMethod));

Maybe instead of taking in a Func<,,> delegate, you should consume a Comparison<> delegate. Because that's what List<> wants (for historical reasons; the List<>.Sort method was written for .NET 2.0, before the Func delegates were introduced).

Therefore:

public static string BuildHumanSitemap(Comparison<TreeNode> sortMethod, params string[] classNames)
{
  //calling list sort on method passed as parameter
  nodes.Sort(sortMethod);
}

Then call your method very simply like this:

BuildHumanSitemap(SortByDateCreated);

where SortByDateCreated is the "method group" from your question.

There's no need for first creating a delegate instance of type Func<TreeNode, TreeNode, int> and then create another delegate instance (of type Comparison<TreeNode> ) which references the first one.

Of course you can also call your BuildHumanSitemap method with a lambda arrow as the first argument.

It works this way:

  TreeView.TreeViewNodeSorter = new CustomNodeSorter();

  private class CustomNodeSorter : IComparer
  {
     public int Compare(object x, object y)
     {
         DateTime xT = (DateTime)x["DocumentCreatedWhen"];
         DateTime yT = (DateTime)y["DocumentCreatedWhen"];
         return xT.CompareTo(yT);
     }
  }

Solution with IComparer<T> .

Comparer

public class MyTreeNodeComparer : IComparer<TreeNode>
{
     public int Compare(TreeNode x, TreeNode y)
     {
         DateTime xT = (DateTime)x["DocumentCreatedWhen"];
         DateTime yT = (DateTime)y["DocumentCreatedWhen"];
         return xT.CompareTo(yT);
     }
}

Usage

list.Sort(new MyTreeNodeComparer());

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM