How to create extension method on generic collecti

2019-03-12 05:44发布

I have a list that contains FrameworkElements and I want to create an extension method called MoveToTop. All this will do is accept an item that is part of that list and move it to the beginning of the list. I know this could be accomplished without the use of an extension method, but I would like it to be implemented as an extension method.

I am having trouble trying to figure out the syntax for creating an extension method that accepts a generic parameter. I know this isn't correct, but if someone could give me an idea how how to accomplish this, I would appreciate it.

public static class Extensions
{
    public static void MoveToTop(this ICollection<T> sequence)
    {
        //logic for moving the item goes here.
    }
}

标签: c# .net oop
1条回答
该账号已被封号
2楼-- · 2019-03-12 06:16

You were close, just need the <T> after the method name before the parenthesis. That's where the generic type parameter list for generic methods is placed. It declares the generic type parameters the method will accept, which then makes them available to be used in the arguments, return values, and method body.

public static class Extensions
{
    public static void MoveToTop<T>(this ICollection<T> sequence)
    {
        //logic for moving the item goes here.
    }
}
查看更多
登录 后发表回答