1 回答

TA貢獻1946條經驗 獲得超4個贊
是的,這可以通過反射來實現。您可以使用該Invoke方法。
它看起來像這樣:
MethodInfo method = type.GetMethod(name);
object result = method.Invoke(objectToCallTheMethodOn);
話雖如此,在正常情況下,您不應該使用反射來調用 c# 中的方法。它僅適用于非常特殊的情況。
這是一個完整的例子:
class A
{
public int MyMethod(string name) {
Console.WriteLine( $"Hi {name}!" );
return 7;
}
}
public static void Main()
{
var a = new A();
var ret = CallByName(a, "MyMethod", new object[] { "Taekyung Lee" } );
Console.WriteLine(ret);
}
private static object CallByName(A a, string name, object[] paramsToPass )
{
//Search public methods
MethodInfo method = a.GetType().GetMethod(name);
if( method == null )
{
throw new Exception($"Method {name} not found on type {a.GetType()}, is the method public?");
}
object result = method.Invoke(a, paramsToPass);
return result;
}
這打?。?/p>
Hi Taekyung Lee!
7
- 1 回答
- 0 關注
- 304 瀏覽
添加回答
舉報