简体   繁体   English

在c#扩展函数中使用泛型

[英]using generics in c# extension functions

I am using generics to translate Java code to C# and having trouble with containers of the sort: 我正在使用泛型将Java代码转换为C#并且遇到了类似容器的问题:

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. 列表可以抽象为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) ) (实际上,它可能是ICollection<T> ,因为这(不是IList<T> )定义了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: 我认为Marc Gravell回答得最好 ,但我会补充:

Don't do this at all. 根本不要这样做。 There is no advantage to: 没有优势:

myList.add(obj);

vs VS

myList.Add(obj);

The only "advantage" here is that your resulting C# will look wrong to most developers. 这里唯一的“优势”是大多数开发人员对你的C#看起来都不对。 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. 如果您要从Java移植到C#,那么值得花些额外的时间让您的方法看起来像原生.NET方法一样工作。

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? @Dreamwalker,你的意思? list.Add(obj);

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

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