【问题标题】:Create <Type> of function at runtime [duplicate]在运行时创建函数的 <Type> [重复]
【发布时间】:2021-07-23 11:52:58
【问题描述】:

我是反射领域的新手,我真的需要一些指导,需要将一小段代码转换为对运行时有效。

这部分目前是手动完成的:

Telegram ReqInstance = new Telegram();
Telegram ResInstance = await comm.SendMethodAsync<Telegram>(ReqInstance)

但我需要在运行时执行此操作, 第一部分我已经成功完成(创建实例),但我不知道如何调用 await 部分

Type type = typeof(Telegram);
Assembly assembly = Assembly.GetAssembly(type);
Object instance = Activator.CreateInstance(assembly.FullName, "Telegram").Unwrap();

【问题讨论】:

  • 您希望方法名称发生变化吗?为什么首先需要反思?
  • 是的,我有 Telegram1,然后是 Telegram2,但这里我只举了一个例子
  • 这些课程是你自己做的吗?您的子类之间是否有共同的接口或基类可以让您使用泛型而不是反射?
  • 是的,但是那些类型 Telegram1Telegram2 unknown 在编译时?还是你都知道,都编译了,只是这样的类型非常多?
  • 无论如何,这是您对您提出的确切问题的回答:stackoverflow.com/a/4101821/717732

标签: c# reflection .net-assembly


【解决方案1】:

你没有指定comm是什么,所以我会根据你指定的细节给你答案。

您需要使用Invoke 方法才能调用SendMethodAsync 方法。为此,您可以使用方法SendMethodAsynccomm 类中实现interface。然后在通用部分,您应该检查 comm 是否正在实现 interface 以确保该方法存在。然后您调用并在方法名称中执行以下操作:

MethodInfo method = commType.GetMethod(nameof(YourInterface.SendMethodAsync));
Telegram ResInstance = await (Task<Telegram>)method.Invoke(comm, ReqInstance);

此外,您可能需要在方法变量上使用MakeGenericMethod 并将类型作为参数传递。

【讨论】:

    猜你喜欢
    • 2014-12-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-03-15
    • 2012-07-02
    相关资源
    最近更新 更多