我想重载通用列表的 Add 方法,以便我可以使用集合初始化,例如:
var x = new List<Tuple<string>> { { "1", "2" }, { "1", "2" } };
Run Code Online (Sandbox Code Playgroud)
(其中 Tuple 是二进制元组的简单自定义实现。)但是,我创建了一个扩展方法,在 cs 文件中放置了一个 using 指令,但仍然得到“方法 'Add' 没有重载需要 2 个参数”错误。
是不是不可能(使用扩展方法)?
扩展方法代码:
namespace ExtensionMethods {
public static class Extensions{
public static void Add<T>(this List<Tuple<T>> self, T value1, T value2) {
self.Add(new Tuple<T> { value1, value2 });
}
}
}
Run Code Online (Sandbox Code Playgroud)
在 C# 6.0[0] 中,Microsoft 允许在集合初始值设定项中使用扩展方法。万岁:)
由于这不是 .NET Framework 或 CLR 更改,而是编译器更改,因此此功能可以与 .NET 4.0 一起使用。
因此,以下是现在有效的 C# 代码。(在 Visual Studio 2015 RC 中测试)
class Program
{
static void Main(string[] args)
{
var x = new List<Tuple<string,string>> { { "1", "2" }, { "1", "2" } };
}
}
public static class Extensions
{
public static void Add<T1,T2>(this List<Tuple<T1,T2>> self, T1 value1, T2 value2)
{
self.Add(Tuple.Create( value1, value2 ));
}
}
Run Code Online (Sandbox Code Playgroud)
C# 6 特性[0]
| 归档时间: |
|
| 查看次数: |
2640 次 |
| 最近记录: |