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