简体   繁体   English

有没有办法为 C# 中的自定义 class 的通用集合创建方法?

[英]Is there a way to create a method for a generic collection of a custom class in C#?

I was wondering if this was at all possible.我想知道这是否可能。 Since I´m not all right there with IEnumerator/IEnumerables, there might be a way to do it I don´t know.因为我对 IEnumerator/IEnumerables 不太满意,所以我不知道可能有办法做到这一点。 I imagine it would go something like this:我想它会 go 是这样的:

public namespace cookietest
{
    public static class Program{
        public List<Cookie> cookies = new List<Cookie>();
        CookieJar cookieJar = cookies.ToCookieJar();
    }

    public class Cookie{
        public int size;
        //Implementatin of ToCookieJar()
    }
}

I understand that there are better design solutions and that this isn't really a problem, but I got curious and couldn't find anything about it.我知道有更好的设计解决方案,这不是一个真正的问题,但我很好奇,找不到任何关于它的信息。

What you are looking for is called extension methods .您正在寻找的是所谓的扩展方法

Given a reference type, such as List<T> , you can "extend" it with your own methods like this:给定一个引用类型,例如List<T> ,您可以使用自己的方法“扩展”它,如下所示:

public static class Program
{
    public List<Cookie> cookies = new List<Cookie>();
    CookieJar cookieJar = cookies.ToCookieJar();
}

public class Cookie
{
    public int size;
}

public static class CookieExtensions
{
    public static CookieJar ToCookieJar(this IEnumerable<Cookie> list)
    {
        return new CookieJar(list);
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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