Skip to main content
 首页 » 编程设计

C# 类型 GetMethod() 其中参数顺序是随机的

2024年02月05日14kenshinobiy

我正在尝试获取一个对象的方法,如果该方法的参数与我提供的参数列表的顺序相匹配,它就可以正常工作。我试图避免这种情况,因此我不必担心跨不同文件的方法中参数类型的顺序。这是我的东西

MethodInfo mi = stateType.GetMethod("Entrance", typesToUse.ToArray()); 

在我的测试用例中,typesToUse 只包含两个唯一接口(interface)的实例, IClass1 和 IClass2 的顺序。

如果入口方法是:Entrance(IClass1 c1, IClass2 c2),它会选择这个方法。虽然,如果它的入口(IClass2 c2,IClass1 c1),它不会,然后 mi 将为空。

有解决办法吗?也许是一种告诉 GetMethod 忽略参数顺序的方法?

感谢任何帮助。

请您参考如下方法:

实现一个忽略参数顺序的方法是不明智的。参数顺序对于确定您是否找到了正确的方法至关重要。

考虑这个简单的类:

public class A  
{ 
    public void Foo(int a, string b) 
    { 
        PrintAString(); 
    } 
 
    public void Foo(string b, int a) 
    { 
        FormatHardDrive(); 
    } 

如果您的方法忽略了参数顺序...可能会发生不好的事情!

说了这么多,当然是有可能的。只需获取具有给定名称的所有方法,消除所有不包含 typesToUse 中所有类型参数的方法,然后确保只有一个。

下面的代码演示了这一点:

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Reflection; 
 
public class Program 
{ 
    public static void Main() 
    { 
        var typesToUse = new Type[] { typeof(int), typeof(string) }; 
        var methods = typeof(A).GetMethods().Where(m => m.Name == "Foo"); 
 
        var matchingMethods = methods.Where(m => ContainsAllParameters(m, typesToUse)); 
 
        Console.WriteLine(matchingMethods.Single()); 
    } 
 
    private static bool ContainsAllParameters(MethodInfo method, Type[] typesToUse)  
    { 
        var methodTypes = method.GetParameters().Select(p => p.ParameterType).ToList(); 
 
        foreach(var typeToUse in typesToUse) 
        { 
            if (methodTypes.Contains(typeToUse)) 
            { 
                methodTypes.Remove(typeToUse); 
            } 
            else  
            { 
                return false;        
            } 
        } 
 
        return !methodTypes.Any(); 
    } 
 
} 
 
public class A 
{ 
    public void Foo(string a, int b)  
    { 
        Console.WriteLine("Hello World"); 
    } 
}