繁体   English   中英

创建一个方法的DeclaringType实例:Activator.CreateInstance

[英]Create an instance of the DeclaringType of a method: Activator.CreateInstance

我又一次在反思中挣扎。 我只是给你我的调试器不咬的一段代码:

public bool HandleCommand(string command)
        {
            
            MethodInfo m = methods.FirstOrDefault(t => t.GetCustomAttribute<CommandAttribute>().Name == command);
            ICommandSet set =(m.DeclaringType)Activator.CreateInstance(m.DeclaringType);
            m?.Invoke(set, null);
            return true;
        }

基本上,此代码位于名为 CommandHandler 的 class 中。 当它被构造时,它会循环执行程序集中实现某个接口的所有类型,并将它们所有附加了 CustomAttribute 的方法存储在 List 中; 对于这个问题的目的,我只是假设一切都在那里工作。 该属性只有一个属性:

[AttributeUsage(AttributeTargets.Method)]
    public class CommandAttribute : Attribute
    {
        public string Name { get; set; }

        public CommandAttribute(string name)
        {
            Name = name;
        }
    }

现在,在您在上面看到的方法中,HandleCommand() 方法中,我存储的方法的 name 属性等于我在 MethodInfo m 中传入的字符串。 现在我的问题本质上是,我如何正确调用此方法。 m.Invoke 需要一个调用它的 object,并且因为传入“this”不起作用,并且在线示例总是传入它定义的 class 的实例,我想我需要创建一个 ZA2F2ED4F8EBC2CBB4C21A2 的实例是在中定义并将其传递给 Invoke() 方法。 在实践中,这比我想象的要困难得多,我最好的猜测是你可以在上面看到的,使用激活器。

ICommandSet set =(m.DeclaringType)Activator.CreateInstance(m.DeclaringType);

首先,我确定 m 中声明的 class 实现了 ICommandSet,因为这是要检查方法的类型的 creterium。 所以这就是我说“ICommandSet set”的原因。 然后激活器将创建这个实例。 但它不起作用。 提供的唯一错误消息指出 m 是一个变量,但用作类型。 但是,当我将它作为参数传递给 Activator.CreateInstance() 时,编译器似乎可以很好地挖掘它。 我绝对不知道如何解决这个问题,因为我真的不明白问题出在哪里。 有没有人可以帮助我?

另外,所有方法都定义在不同的类甚至项目中,所以我不知道这些方法定义在哪个 class 中。

您收到此消息的原因是您的语法错误。 您不能使用变量取消引用作为期望类型来执行强制转换。 正如您已经知道的那样,您希望将“set”视为“ICommandSet”强制转换。

var set = (ICommandSet) Activator.CreateInstance(m.DeclaringType);

你也可以安全地做

var set = Activator.CreateInstance(m.DeclaringType) as ICommandSet;

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM