调用具有不同参数的方法

时间:2017-07-25 12:19:13

标签: c# method-invocation

我在调用具有不同类型参数的不同方法时面临一个问题。例如。我有3个方法A,B,C,参数如下。

A(string text, int num)

B(bool type, int num2)

C(string text2, boolean type2, int num3)

现在如何逐个调用这三种方法?方法名称作为字符串提取并存储在数组中,在存储之后,需要使用For Each循环调用方法。

enter image description here

1 个答案:

答案 0 :(得分:2)

您可以将Dictionary方法名称和参数保留为stringobject[]

Dictionary<string, object[]> methodsInfo = new Dictionary<string, object[]>
{
    { "A", new object[] { "qwe", 4 }},
    { "B", new object[] { true, 5 }},
    { "C", new object[] { "asd", false, 42 }}
};

使用Invoke

中的MethodInfo调用它们
foreach (KeyValuePair<string, object[]> methodInfo in methodsInfo)
{
    GetType().GetMethod(methodInfo.Key).Invoke(this, methodInfo.Value);
}

如果方法在另一个类中,则可以像这样调用它们

Type classType = Type.GetType("namespace.className");
object classObject = classType.GetConstructor(Type.EmptyTypes).Invoke(new object[] { });

foreach (KeyValuePair<string, object[]> methodInfo in methodsInfo)
{
    classType.GetMethod(methodInfo.Key).Invoke(classObject, methodInfo.Value);
}

注意:GetConstructor(Type.EmptyTypes)用于空构造函数,对于参数化构造函数(比如int)请使用GetConstructor(new[] { typeof(int) }).Invoke(new object[] { 3 }

相关问题