简体   繁体   中英

using generics in c# extension functions

I am using generics to translate Java code to C# and having trouble with containers of the sort:

public static class MyExtensions
{
    public static void add(this List<object> list, object obj)
    {
        list.Add(obj);
    }
    public static void add(this List<string> list, string s)
    {
        list.Add(s);
    }
}

It seems that the generics are lost in comparing arguments and the two methods collide. I'd like any advice on whether generics can be used in this way. Is it possible to support all list operations with a single:

    public static void add(this List<object> list, object obj)
    {
        list.Add(obj);
    }

for example?

SUMMARY All responses have the same solution. List can be abstracted to ICollection. Overall it's probably not a good idea for production code.

How about:

public static void add<T>(this IList<T> list, T value)
{
    list.Add(value);
}

(actually, it could be ICollection<T> , since this (not IList<T> ) defines Add(T) )

Have you tried:

public static void add<T>(this List<T> list, T obj)
{
    list.Add(obj);
}

I'm not sure if you'd want to constrain it to a class or not, but that should do what you're describing.

Do you mean this:

public static void add<T>(this List<T> list, T obj)
{
    list.Add(obj);
}

I think Marc Gravell answered this best , but I will add:

Don't do this at all. There is no advantage to:

myList.add(obj);

vs

myList.Add(obj);

The only "advantage" here is that your resulting C# will look wrong to most developers. If you're going to port from Java to C#, it's worth taking the extra time to make your methods look and work like native .NET methods.

The most versatile way:

public static void add<T>(this ICollection<T> list, T obj) // use ICollection<T>
{
    list.Add(value);
}

@Dreamwalker, did you mean? list.Add(obj);

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