Microsoft MVP성태의 닷넷 이야기
.NET Framework: 259. Type.GetMethod - System.Reflection.AmbiguousMatchException [링크 복사], [링크+제목 복사],
조회: 24681
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 2개 있습니다.)

Type.GetMethod - System.Reflection.AmbiguousMatchException

간단하게, 다음과 같은 예제에서는 GetMethod 실행 시 AmbiguousMatchException 예외가 발생합니다.

class Program
{
    static void Main(string[] args)
    {
        MethodInfo methodInfo = typeof(Program).GetMethod("Test", BindingFlags.Instance | BindingFlags.NonPublic);
    }

    void Test()
    {
    }

    void Test(int a)
    {
    }
}

// 실행 결과:
System.Reflection.AmbiguousMatchException was unhandled
  Message=Ambiguous match found.
  Source=mscorlib
  StackTrace:
       at System.RuntimeType.GetMethodImpl(String name, BindingFlags bindingAttr, Binder binder, CallingConventions callConv, Type[] types, ParameterModifier[] modifiers)
       at System.Type.GetMethod(String name, BindingFlags bindingAttr)
       at ConsoleApplication1.Program.Main(String[] args) in D:\...\Program.cs:line 14
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean ignoreSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()
  InnerException: 

아쉽게도, "MethodInfo []" 반환값을 갖는 GetMethod가 제공되지 않아서 잘못 생각하면 다음과 같이 코딩을 해야 할 수도 있습니다.

MethodInfo [] methodInfos = typeof(Program).GetMethods(BindingFlags.Instance | BindingFlags.NonPublic);
List<MethodInfo> list = new List<MethodInfo>();
foreach (var item in methodInfos)
{
    if (item.Name == "Test")
    {
        list.Add(item);
    }
}

하지만, 잠시 생각을 한 번만 더하면 ^^ 간단한 해결책이 나옵니다.

MemberInfo[] memberInfos = typeof(Program).GetMember("Test", BindingFlags.Instance | BindingFlags.NonPublic);
foreach (var item in memberInfos)
{
    MethodInfo methodInfo = item as MethodInfo;
    Console.WriteLine(methodInfo.Name);
}




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 6/12/2021]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 181  182  183  184  185  186  187  188  189  190  191  192  193  194  [195]  ...
NoWriterDateCnt.TitleFile(s)
107정성태3/1/200520093COM 개체 관련: 15. COM: Control 유형인 경우, IObjectWithSite 를 구현해도 SetSite/GetSite 가 호출이 안됨
106정성태2/28/200519525COM 개체 관련: 14. 탐색기 "처럼" 파일 열기
105정성태2/28/200518480.NET Framework: 26. VS.NET 2005 : 설치 프로젝트 - .NET Framework 설치 강제화
139정성태11/14/200516776    답변글 .NET Framework: 26.1. ^^ 역시, 배려가 되어 있네요. 제가 못 찾은 것이었습니다.
104정성태2/27/200519387VS.NET IDE: 23. MSI 설치 중에 GetLocalTime / GetSystemTime API 사용
132정성태3/30/200519045    답변글 VS.NET IDE: 23.1. [추가]: MSI 설치 동작 원리
102정성태2/16/200521831.NET Framework: 25. Verify that you are a member of the 'Debugger Users' group on the server. [2]
101정성태2/15/200519637.NET Framework: 24. WMI Win32_NTLogEvent 관리 이벤트를 Windows 2000 에서는 "Access Denied" 가 발생하는 문제파일 다운로드1
100정성태2/15/200525915VS.NET IDE: 22. 방화벽 환경에서의 WMI 연결을 위한 포트 설정 [2]
99정성태2/15/200523999COM 개체 관련: 13. 비동기 Drag & Drop 구현 : IAsyncOperation
103정성태2/23/200520012    답변글 COM 개체 관련: 13.1. [관련 자료] 그외 Drag & Drop 링크파일 다운로드1
97정성태2/14/200522705VS.NET IDE: 21. 설치된 Platform SDK 버전확인 방법
96정성태2/14/200524729기타: 9. http://www.google.com/webhp?complete=1&hl=en 검색에 관해서.
95정성태2/14/200534183VS.NET IDE: 20. Win32 특권 정리 [1]
94정성태1/29/200525411VC++: 13. VS.NET 2005 VC++ 컴파일러 에러 : cannot instantiate abstract class
93정성태1/29/200521257VS.NET IDE: 19. 혹시 VS.NET 2005 Beta2(2004/12 CTP Team System 버전)이 다운이 자주 되나요? [2]
92정성태1/29/200519905.NET Framework: 23. Unmanaged 환경에서 Managed DLL에 정의된 메서드 호출 시 오류 확인하는 방법
91정성태11/14/200520535VC++: 12. VS.NET 2005 VC++ Debug: Expression: ( (state != ST_INVALID ) )
90정성태1/27/200521540.NET Framework: 22. Debug: The underlying connection was closed: Unable to connect to the remote server.
89정성태1/26/200526060VC++: 11. Delay Loaded DLL
87정성태1/23/200519611VS.NET IDE: 18. VS.NET 2005 Beta 1 - VC++ 프로젝트에서 Connection Point 구현시 버그
88정성태1/23/200519098    답변글 VS.NET IDE: 18.1. VS.NET 2003 : VC++ 프로젝트에서 Connection Point 추가시에도 버그
86정성태1/23/200525047.NET Framework: 21. Code Snippet - Enum과 관련된 다양한 형변환 [1]
85정성태1/23/200523231스크립트: 4. Windows 2003에서 BHO(Browser Helper Objects) 동작 안하는 현상 [1]
83정성태1/18/200528377.NET Framework: 20. System.AccessViolationException 예외가 발생한 한 예.
82정성태1/3/200521868VS.NET IDE: 17. Windows 운영 - 특정 사용자 또는 그룹에 대해서 파일 공유 접근 금지
... 181  182  183  184  185  186  187  188  189  190  191  192  193  194  [195]  ...