使用反射获取实现接口的所有类,并且仅初始化与给定ID /操作码匹配的类

问题描述

因此,在下面的代码中,有一个指令接口,该接口被许多类(例如AddInstruction,DivideInstruction等)使用。实现该接口的每个类都按照Instruction接口分配标签和操作码。

Instruction.cs

public abstract class Instruction
    {
        private string label;
        private string opcode;

        protected Instruction(string label,string opcode)
        {
            this.label = label;
            this.opcode = opcode;
        }

        public abstract void Execute(Machine m);
    }

所有指令均具有相同基本功能的众多指令之一的示例

AddInstruction.cs

public class AddInstruction : Instruction
    {
        
        private int reg,s1,s2;

        public AddInstruction(string lab,int reg,int s1,int s2) : base(lab,"add") // here the base interface is Instruction and we are assigning the opcode as add,other instructions have there own opcodes //
        {
            this.reg = reg;
            this.s1 = s1;
            this.s2 = s2;
        }

        public override void Execute(Machine m) =>
            // do something
}

从这里开始,我想将工厂模式与Reflection一起使用,以便将来可以根据提供的操作码来启动具有自己操作码的新指令。

InstructionFactoryInterface.cs

interface InstructionFactoryInterface
    {
        Instruction GetInstruction(string opcode);
    }

InstructionFactory.cs

class InstructionFactory : InstructionFactoryInterface
    {
        public Instruction GetInstruction(string opcode)
        {
            Type type = typeof(Instruction);
            var types = AppDomain.CurrentDomain.GetAssemblies()
                .SelectMany(s => s.GetTypes())
                .Where(p => type.IsAssignableFrom(p));
            foreach (var type1 in types)
            {
                // loop through all the types and only return the class that has a matching opcode //
            }
   }

现在这是我很烂的地方,我如何遍历实现Instruction接口的所有类型,而只返回与传入的opcode参数匹配的类型。谢谢

解决方法

使用字典和将已知操作与工厂方法(或委托)一起注册更容易

public static Dictionary<string,Func<string,int,Instruction>> FactoryDict
{ get; } = new Dictionary<string,Instruction>> {
    ["add"] = (lab,reg,s1,s2) => new AddInstruction(lab,s2),["sub"] = (lab,s2) => new SubInstruction(lab,//...
};

请注意,您不必使用所有参数:

    ["nop"] = (lab,s2) => new NopInstruction(lab,reg),

然后您可以通过获取说明

public Instruction GetInstruction(string opcode,string lab,int reg,int s1,int s2)
{
    if (FactoryDict.TryGetValue(opcode,out var create)) {
        return create(lab,s2);
    }
    return null;
}

如果您使用命名约定,例如指令类的名称是带有大写首字母+“指令”的操作码:

public Instruction GetInstruction(string opcode,int s2)
{
    // E.g. make "AddInstruction" out of "add"
    string instructionName = $"{Char.ToUpper(opcode[0])}{opcode.Substring(1)}Instruction";

    Type baseType = typeof(Instruction);
    Type instructionType = AppDomain.CurrentDomain.GetAssemblies()
        .SelectMany(s => s.GetTypes())
        .Where(p => baseType.IsAssignableFrom(p) &&
                    !p.IsAbstract &&
                    p.Name == instructionName)
        .FirstOrDefault();
    if (instructionType != null) {
        return (Instruction)Activator.CreateInstance(instructionType,lab,s2);
    }
    return null;
}

此外,始终使用标准化参数列表的构造函数会使事情变得更容易。

,

这有点棘手,因为AddInstruction没有默认的构造函数。话虽如此,它可以做到。您将需要使用FormatterServices.GetUninitializedObject()来获取实例,而无需使用构造函数。基类Instruction也将需要修改,因此opcode不是字段,而是在每个子类中实现的方法。这是一个示例:

using System;
using System.Runtime.Serialization;

namespace Generator
{
    public class Program
    {
        public static void Main()
        {
            var add = FormatterServices.GetUninitializedObject(typeof(AddInstruction));
            var opcode = ((Instruction) add).GetOpCode();
            
            Console.WriteLine(opcode);
        }
    }

    public abstract class Instruction
    {
        public abstract string GetOpCode();
    }

    public class AddInstruction : Instruction
    {
        private int s1,s2;

        public AddInstruction(int s1,int s2)
        {
            this.s1 = s1;
            this.s2 = s2;
        }

        public override string GetOpCode()
        {
            return "add";
        }
    }
} 
,

System.Reflection API不允许您从构造函数主体获取IL指令。因此,您无法确定特定类的构造函数将哪个参数传递给基本构造函数。

您可以使用Mono.Cecil库(也可以与.NET Framework一起使用)完成此任务。

class InstructionFactory : InstructionFactoryInterface {
    static readonly IDictionary<string,Type> Instructions = new Dictionary<string,Type>();
    static InstructionFactory() {
        InitializeDictionary();
    }
    static void InitializeDictionary() {
        Type type = typeof(Instruction);
        var types = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(s => s.GetTypes())
            .Where(p => type.IsAssignableFrom(p));
        foreach(var type1 in types) {
            try {
                string type1Opcode = GetOpcode(type1);
                Instructions.Add(type1Opcode,type1);
            } catch(InvalidOperationException ex) {
                LogError(ex);
            }
        }
    }
    static void LogError(InvalidOperationException ex) {
        // ...
    }
    public Instruction GetInstruction(string opcode,params object[] args) {
        Type instructionType;
        bool found = Instructions.TryGetValue(opcode,out instructionType);
        if(!found) {
            throw new InvalidOperationException($"Instruction {opcode} not found");
        }
        return (Instruction)Activator.CreateInstance(instructionType,args);
    }
    static readonly IDictionary<string,AssemblyDefinition> AssemblyDefinitions = new Dictionary<string,AssemblyDefinition>();
    static AssemblyDefinition GetAssemblyDefinition(Type type) {
        AssemblyDefinition ad;
        bool found = AssemblyDefinitions.TryGetValue(type.Assembly.Location,out ad);
        if(!found) {
            ad = AssemblyDefinition.ReadAssembly(type.Assembly.Location);
            AssemblyDefinitions.Add(type.Assembly.Location,ad);
        }
        return ad;
    }
    static string GetOpcode(Type type) {
        AssemblyDefinition adType = GetAssemblyDefinition(type);
        TypeDefinition tdType = adType.MainModule.GetType(type.FullName);
        IEnumerable<MethodDefinition> ctors = tdType.GetConstructors();
        AssemblyDefinition adInstruction = GetAssemblyDefinition(typeof(Instruction));
        TypeDefinition tdInstruction = adInstruction.MainModule.GetType(typeof(Instruction).FullName);
        MethodDefinition ctorInstruction = tdInstruction.GetConstructors().Single();
        foreach(MethodDefinition ctor in ctors) {
            for(int i = 0; i < ctor.Body.Instructions.Count; i++) {
                Mono.Cecil.Cil.Instruction instr = ctor.Body.Instructions[i];
                if(instr.OpCode.Code == Code.Call && instr.Operand is MethodDefinition md && md == ctorInstruction) {
                    Mono.Cecil.Cil.Instruction lastParameter = ctor.Body.Instructions[i - 1];
                    return (string)lastParameter.Operand;
                }
            }
        }
        throw new InvalidOperationException($"{type.FullName} does not call the base constructor");
    }
}
,

如何使用属性?对于未来,它是非常可扩展的。尽管由于您的操作码只是一个字符串,所以您在字符串比较和唯一性方面都必须谨慎,因为将来您最终可能会遇到两个共享相同操作码的类。

自定义属性类:

[Instruction("the opCode associated with this type")]
public class AddInstruction : Instruction
{
    // rest of class
}

标记派生类:

class InstructionFactory : InstructionFactoryInterface
{
    public Instruction GetInstruction(string opcode)
    {
        Type type = typeof(Instruction);
        var types = AppDomain.CurrentDomain.GetAssemblies()
            .SelectMany(s => s.GetTypes())
            .Where(p => type.IsAssignableFrom(p));
        foreach (var type1 in types)
        {
            var att = type1.GetCustomAttribute<InstructionAttribute>(false); // don't check ancestors; only this type
            string attributeOpCode = att?.OpCode;
            if (!string.IsNullOrWhiteSpace(attributeOpCode) && attributeOpCode == opcode)
            {
                // construct an instance of type1 however you prefer,return it
            }
        }
        return null; // or other error handling
    }
}

更改为使用该属性来查找所需类型的InstructionFactory:

sign_in_button1=driver.find_element_by_xpath('''/html/body/div[8]/div[3]/div/div/div/div/div[2]/main/div[1]/section/div[2]/div[1]/div[1]/div/div/img''')

此后,您可以添加任意数量的从Instruction派生的新类-您只需为它们分配要用作标识符的操作码字符串即可。

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...