오류가있는 줄에서 컴파일러가 T
매개 변수가있는 메서드를 해상도로 선택하기 때문에 컴파일되지 않습니다. 이는 List<T>
이 a의 일반 제약 조건에 맞지 않기 때문에 실패합니다. 싱글 T
. 컴파일러는 사용할 수있는 또 다른 메소드가 있음을 인식하지 못합니다. 단일 T
메서드를 제거하면 컴파일러에서 여러 개체에 대한 메서드를 올바르게 찾습니다.일반 확장 메서드 확인이 실패합니다.
일반적인 방법 해상도에 대한 블로그 게시물 두 개를 읽었습니다. 하나는 JonSkeet here이고 다른 하나는 Eric Lippert here에서 가져 왔지만 설명이나 문제를 해결할 방법을 찾을 수 없습니다.
분명히, 다른 이름을 가진 두 가지 메소드를 사용하면 효과가있을 것입니다. 그러나 저는이 경우에 대해 하나의 메소드가 있다는 점을 좋아합니다. 드미트리 제안으로 두 번째를 다음과 같은 방법으로 호출하여,
public static void Method(this SomeInterface parameter) { /*...*/ }
을 또는 :
instances.Method<SomeImplementation>();
을
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();'을 (를) 사용해 보셨습니까? –
Dmitry
@ 드미트리는 실제로 작동 할 것입니다. 나는 몇 가지 것을 시험 할 것이다. – nvoigt