【发布时间】:2014-04-22 11:00:16
【问题描述】:
下面的程序没有编译,因为在报错的那一行,编译器选择了带有单个T参数的方法作为解析,失败是因为List<T>不符合单个参数的泛型约束T。编译器无法识别可以使用另一种方法。如果我删除单个T 方法,编译器将正确找到许多对象的方法。
我已经阅读了两篇关于泛型方法解析的博文,一篇来自 JonSkeet here,另一篇来自 Eric Lippert here,但我找不到解释或解决问题的方法。
显然,有两个不同名称的方法会起作用,但我喜欢你只有一个方法来处理这些情况。
namespace Test
{
using System.Collections.Generic;
public interface SomeInterface { }
public class SomeImplementation : SomeInterface { }
public static class ExtensionMethods
{
// comment out this line, to make the compiler chose the right method on the line that throws an error below
public static void Method<T>(this T parameter) where T : SomeInterface { }
public static void Method<T>(this IEnumerable<T> parameter) where T : SomeInterface { }
}
class Program
{
static void Main()
{
var instance = new SomeImplementation();
var instances = new List<SomeImplementation>();
// works
instance.Method();
// Error 1 The type 'System.Collections.Generic.List<Test.SomeImplementation>'
// cannot be used as type parameter 'T' in the generic type or method
// 'Test.ExtensionMethods.Method<T>(T)'. There is no implicit reference conversion
// from 'System.Collections.Generic.List<Test.SomeImplementation>' to 'Test.SomeInterface'.
instances.Method();
// works
(instances as IEnumerable<SomeImplementation>).Method();
}
}
}
【问题讨论】:
-
你试过
instances.Method<SomeImplementation>();吗? -
@Dmitry 确实可行。我会测试一些东西。
标签: c# generics extension-methods overload-resolution