c# - 使用枚举参数获取歧义方法
问题描述
我正在尝试从动态加载的程序集中调用方法。方法是模棱两可的。
例如: 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
解决方案
您应该能够使用 获取枚举的类型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
推荐阅读
- jhipster - 如何在 Jhipster JDL 中为实体属性设置初始值?
- javascript - 隐藏所有具有 ID 的元素
- java - 如果条件超过某个数量的分区(在我的情况下为 30)并且如果分区小于 30,则 Hive 查询抛出语义异常
- matlab - 分组十六进制颜色值
- docker - 如何通过 docker compose 将文件复制到 docker 容器,而不绑定到主机?
- python - 在 Excel 文件中获取指向 PDF 中特定页面的超链接
- python - 熊猫造型:将数字格式导出到 excel
- c - 如何在“;”之前修复预期的标识符 令牌错误
- spring-boot - 使用 Spring boot + WebFlux 进行全局错误处理
- r - 以特定顺序将列重塑为行