如何创建泛型集合扩展方法 [英] How to create extension method on generic collection

查看:219
本文介绍了如何创建泛型集合扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含FrameworkElements名单,我想创建一个名为MoveToTop扩展方法。这一切都将做的是接受作为该列表的一部分的项目,并将其移动到列表的开头。我知道这可以在不使用扩展方法来完成,但我想它被实现为一个扩展方法。



我有麻烦试图找出语法用于创建一个接受泛型参数的扩展方法。我知道这是不正确的,但如果有人可以给我一个想法如何如何做到这一点,我将不胜感激。

 公共静态类扩展
{
公共静态无效MoveToTop(这ICollection的< T>序列)
{
//逻辑移动项目放在这里。
}
}


解决方案

您接近,只需要在< T> 的括号之前的方法名称后。这就是对泛型方法泛型类型参数列表放置。它声明泛型类型参数的方法会接受,然后让他们提供的参数使用,返回值和方法体。

 公共静态类扩展
{
公共静态无效MoveToTop< T>(这ICollection的< T>序列)
{
//逻辑移动的项目放在这里。
}
}


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.
    }
}

解决方案

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.
    }
}

这篇关于如何创建泛型集合扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆