C# 重载泛型 + 运算符
C# Overload generic + operator
我正在尝试通过向其中添加一个项目来使列表能够被添加。
我正在努力实现的目标代码使用:
List<int> numbers = new List<int>();
numbers += 10;
我试过的。
"operator +" 应该重载 + 并且 "this IList" 应该扩展泛型 IList。
public static IList<T> operator +<T>(this IList<T> list, T element)
{
list.Add(element);
return list;
}
但是它不起作用,在 visual studios 2012 中它上面到处都是红色下划线。
我究竟做错了什么?这不可能吗?为什么这适用于标准 class 但不适用于通用 class?
运算符只能在class的定义中被重载。您不能使用扩展方法从外部覆盖它们。
此外,至少有一个参数必须与 class 的类型相同。
所以你能做的最好的事情是:
public class CustomList<T> : List<T>
{
public static CustomList<T> operator +(CustomList<T> list, T element)
{
list.Add(element);
return list;
}
}
你可以像这样使用:
var list = new CustomList<int> { 1, 2 };
list += 3;
Console.WriteLine(string.Join(", ", list)); // Will print 1, 2, 3
上面接受的答案更适合所问的问题,但除此之外,如果有人需要添加任何类型的两个列表并保留原始列表。我可能应该将其发布在不同的主题上,但在 "overloading + operator in c#" 上进行搜索会将其列为最佳结果。它可能会对某人有所帮助。
void Main()
{
List<string> str = new List<string> {"one", "two", "three"};
List<string> obj = new List<string> {"four", "five", "six", "seven"};
foreach ( string s in str + obj ) Console.Write(s + ", ");
}
public class List<T> : System.Collections.Generic.List<T>
{
public static List<T> operator +(List<T> L1, List<T> L2)
{
List<T> tmp = new List<T>() ;
foreach ( T s in L1 ) tmp.Add(s);
foreach ( T s in L2 ) tmp.Add(s);
return tmp ;
}
}
//one, two, three, four, five, six, seven,
我正在尝试通过向其中添加一个项目来使列表能够被添加。
我正在努力实现的目标代码使用:
List<int> numbers = new List<int>();
numbers += 10;
我试过的。 "operator +" 应该重载 + 并且 "this IList" 应该扩展泛型 IList。
public static IList<T> operator +<T>(this IList<T> list, T element)
{
list.Add(element);
return list;
}
但是它不起作用,在 visual studios 2012 中它上面到处都是红色下划线。 我究竟做错了什么?这不可能吗?为什么这适用于标准 class 但不适用于通用 class?
运算符只能在class的定义中被重载。您不能使用扩展方法从外部覆盖它们。
此外,至少有一个参数必须与 class 的类型相同。
所以你能做的最好的事情是:
public class CustomList<T> : List<T>
{
public static CustomList<T> operator +(CustomList<T> list, T element)
{
list.Add(element);
return list;
}
}
你可以像这样使用:
var list = new CustomList<int> { 1, 2 };
list += 3;
Console.WriteLine(string.Join(", ", list)); // Will print 1, 2, 3
上面接受的答案更适合所问的问题,但除此之外,如果有人需要添加任何类型的两个列表并保留原始列表。我可能应该将其发布在不同的主题上,但在 "overloading + operator in c#" 上进行搜索会将其列为最佳结果。它可能会对某人有所帮助。
void Main()
{
List<string> str = new List<string> {"one", "two", "three"};
List<string> obj = new List<string> {"four", "five", "six", "seven"};
foreach ( string s in str + obj ) Console.Write(s + ", ");
}
public class List<T> : System.Collections.Generic.List<T>
{
public static List<T> operator +(List<T> L1, List<T> L2)
{
List<T> tmp = new List<T>() ;
foreach ( T s in L1 ) tmp.Add(s);
foreach ( T s in L2 ) tmp.Add(s);
return tmp ;
}
}
//one, two, three, four, five, six, seven,