首页 > 解决方案 > 使用枚举参数获取歧义方法

问题描述

我正在尝试从动态加载的程序集中调用方法。方法是模棱两可的。

例如: dll 包含以下方法:

public static string ReadString(string key, KeyType type)
public static string ReadString(string key, string type)

我想用枚举参数KeyType调用那个。

var assembly = Assembly.LoadFile(@"stringutils.dll");
Type type = assembly.GetType("Utils.StringReader");

我试过了

var method = type.GetMethod("ReadString", new[] { typeof(string) });

并尝试过

var method = type.GetMethod("ReadString", new[] { typeof(string), typeof(int) });

但它返回 null

标签: c#reflection

解决方案


您应该能够使用 获取枚举的类型GetType(...),但您可能需要包含命名空间,并且它需要KeyType驻留在您正在加载的程序集中。

您还可以GetMethods()根据任意标准使用和过滤这些方法。例子:

namespace MyNamespace
{
public enum MyEnum
{
    Test1,
    Test2
}
class Program
{
    public static void MyMethod(MyEnum i) => Console.WriteLine($"My Method With {i}");
    public static void MyMethod() => Console.WriteLine("My Method Without Enum");

    static void Main(string[] args)
    {
        var asm = Assembly.GetExecutingAssembly();
        var enumType = asm
            .GetType("MyNamespace.MyEnum");

        var method1 = asm
            .GetType("MyNamespace.Program")
            .GetMethod("MyMethod", new[] { enumType });

        var method2 = asm.GetType("MyNamespace.Program")
            .GetMethods()
            .First(
                m => m.IsStatic &&
                m.IsPublic &&
                m.Name == "MyMethod" &&
                m.GetParameters().Count() == 1);

        var myEnumValue = Enum.ToObject(enumType, 1);
        method1.Invoke(null, new object[] { myEnumValue });
    }
}
}

会输出My Method With Test2


推荐阅读