C#에서 확장 메서드를 식별하기 위해 리플렉션을 어떻게 사용할 수 있습니까?
Jan 06, 2025 am 08:57 AM리플렉션을 사용하여 확장 메서드 식별
C#에서 확장 메서드는 원본을 수정하지 않고도 기존 형식에 새 기능을 추가하는 편리한 방법을 제공합니다. 클래스 정의. 확장 메서드가 클래스에 추가되었는지 확인하는 것은 단위 테스트 또는 적절한 구현 보장과 같은 다양한 시나리오에서 유용할 수 있습니다.
리플렉션을 사용하여 확장 메서드를 식별하려면 먼저 확장이 있는 어셈블리를 살펴봐야 합니다. 메소드를 정의할 수 있습니다. ExtensionAttribute 특성으로 데코레이팅된 클래스를 식별하고 해당 클래스 내의 메서드를 검사합니다. ExtensionAttribute로 표시되고 첫 번째 매개 변수 유형이 조사 중인 유형과 일치하는 모든 메서드는 확장 메서드입니다.
using System; using System.Runtime.CompilerServices; using System.Reflection; using System.Linq; using System.Collections.Generic; public static class FirstExtensions { public static void Foo(this string x) { } public static void Bar(string x) { } // Not an ext. method public static void Baz(this int x) { } // Not on string } public static class SecondExtensions { public static void Quux(this string x) { } } public class Test { static void Main() { Assembly thisAssembly = typeof(Test).Assembly; foreach (MethodInfo method in GetExtensionMethods(thisAssembly, typeof(string))) { Console.WriteLine(method); } } static IEnumerable<MethodInfo> GetExtensionMethods(Assembly assembly, Type extendedType) { var isGenericTypeDefinition = extendedType.IsGenericType &amp;&amp; extendedType.IsTypeDefinition; var query = from type in assembly.GetTypes() where type.IsSealed &amp;&amp; !type.IsGenericType &amp;&amp; !type.IsNested from method in type.GetMethods(BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic) where method.IsDefined(typeof(ExtensionAttribute), false) where isGenericTypeDefinition ? method.GetParameters()[0].ParameterType.IsGenericType &amp;&amp; method.GetParameters()[0].ParameterType.GetGenericTypeDefinition() == extendedType : method.GetParameters()[0].ParameterType == extendedType select method; return query; } }
이 예에서 GetExtensionMethods는 thisAssembly 어셈블리의 문자열 유형에 대한 모든 확장 메서드를 식별합니다. ExtensionAttribute로 장식된 유형을 수집하고 해당 메소드에서 적절한 매개변수 유형 및 ExtensionAttribute를 검사합니다.
위 내용은 C#에서 확장 메서드를 식별하기 위해 리플렉션을 어떻게 사용할 수 있습니까?의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

인기 기사

인기 기사

뜨거운 기사 태그

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











C 언어 함수에 의해 반환 된 값 유형은 무엇입니까? 반환 값을 결정하는 것은 무엇입니까?

STL (정렬, 찾기, 변환 등)의 알고리즘을 효율적으로 사용하려면 어떻게합니까?
