편집 :이 대답은 매개 변수 유형이 아닌 매개 변수 이름에 초점을 맞추고 있습니다. 코드가 혼란 스럽거나 매개 변수 이름이 다른 경우 Jon Skeet이 제공 한 솔루션을 매핑하기가 어려울 수 있습니다.
어쨌든, 나는이 많은 연주했다 .... 이것은 (PARAM 이름을 모르는 상태에서) 나를 위해 잘 작동하는 무슨이다 : 그래서
public object CallMethod(string method, params object[] args)
{
object result = null;
// lines below answers your question, you must determine the types of
// your parameters so that the exact method is invoked. That is a must!
Type[] types = new Type[args.Length];
for (int i = 0; i < types.Length; i++)
{
if (args[i] != null)
types[i] = args[i].GetType();
}
MethodInfo _method = this.GetType().GetMethod(method, types);
if (_method != null)
{
try
{
_method.Invoke(this, args);
}
catch (Exception ex)
{
// instead of throwing exception, you can do some work to return your special return value
throw ex;
}
}
return result;
}
, 위의 함수를 호출 할 수 있습니다 :
public int MyMethodName(int a, string b, char c) {
return 1000;
}
참고 :
object o = CallMethod("MyMethodName", 10, "hello", 'a');
위의 호출은 일치하는 서명이 메소드를 호출 할 수 있어야합니다 위의 예제가 'this
'의 범위에 있습니다.
출처
2012-07-17 17:46:12
KMX
ASP.NET MVC 프레임 워크와 관련된 몇 가지 복잡한 문제로 인해 사용할 수 없습니다. 그러나,이 100 % 질문에 대답했다. 감사! – Pluc
이 방법을 시도했지만 "주어진 키가 사전에 없습니다"라는 메시지가 계속 나타납니다. 내가 무엇이 누락 되었습니까? – Jacques
@Jacques : 자네가 사전에 지정하지 않은 매개 변수가 있다는 것을 제안 할 것이다 ... –