ProgramingTip

리플렉션을 사용하여 .NET에서 오버로드 된 메서드를 호출하는 방법

bestdevel 2020. 11. 14. 10:57
반응형

리플렉션을 사용하여 .NET에서 오버로드 된 메서드를 호출하는 방법


.NET (2.0)에서 리플렉션을 사용하여 호출하는 방법이 오버로드 된 메서드? 공통 기본 클래스에서 파생 된 클래스를 동적으로 인스턴스화하는 응용 프로그램이 있습니다. 동일한 이름의 메소드 2 개 (매개 변수 포함 및 제외)가 포함되어 있습니다. 메서드를 호출해야합니다. 지금 당장은 모호한 메소드를 호출한다고 오류 만 표시됩니다.

그래, 난 할 수 그냥 내 기본 클래스의 인스턴스로 인스턴스를 캐스팅 내가 필요로하는 메서드를 호출합니다. 결국 그렇게 것이지만 지금은 내부 합병증으로 인해 허용되지 않습니다.

어떤 도움이 좋을 것입니다! 감사합니다.


원하는 방법을 지정해야합니다.

class SomeType 
{
    void Foo(int size, string bar) { }
    void Foo() { }
}

SomeType obj = new SomeType();
// call with int and string arguments
obj.GetType()
    .GetMethod("Foo", new Type[] { typeof(int), typeof(string) })
    .Invoke(obj, new object[] { 42, "Hello" });
// call without arguments
obj.GetType()
    .GetMethod("Foo", new Type[0])
    .Invoke(obj, new object[0]);


예. 메서드를 호출 할 때 원하는 오버로드와 일치하는 매개 변수를 전달합니다.

예를 들면 :

Type tp = myInstance.GetType();

//call parameter-free overload
tp.InvokeMember( "methodName", BindingFlags.InvokeMethod, 
   Type.DefaultBinder, myInstance, new object[0] );

//call parameter-ed overload
tp.InvokeMember( "methodName", BindingFlags.InvokeMethod, 
   Type.DefaultBinder, myInstance, new { param1, param2 } );

만약 당신이 반대 방향으로 제안한다면 (즉, MemberInfo를 찾고 호출하여) 올바른 것을 얻도록주의하십시오. 매개 변수가없는 오버로드가 처음 발견 될 수 있습니다.


System.Type []을 사용하고 빈 Type []을 전달하는 GetMethod 오버로드를 사용합니다.

typeof ( Class ).GetMethod ( "Method", new Type [ 0 ] { } ).Invoke ( instance, null );

참고 URL : https://stackoverflow.com/questions/223495/how-to-use-reflection-to-invoke-an-overloaded-method-in-net

반응형