Activator.CreateInstance can't find the constructor (MissingMethodException)

后端 未结 9 2242
一个人的身影
一个人的身影 2021-02-18 15:55

I have a class which has the following constructor

public DelayCompositeDesigner(DelayComposite CompositeObject)
{
    InitializeComponent();

    compositeObjec         


        
9条回答
  •  野趣味
    野趣味 (楼主)
    2021-02-18 16:38

    I found a solution to the problem, I was struggling with the same issue.

    Here is my activator:

    private void LoadTask(FileInfo dll)
        {
            Assembly assembly = Assembly.LoadFrom(dll.FullName);
    
            foreach (Type type in assembly.GetTypes())
            {
                var hasInterface = type.GetInterface("ITask") != null;
    
                if (type.IsClass && hasInterface)
                {
                    var instance = Activator.CreateInstance(type, _proxy, _context);
                    _tasks.Add(type.Name, (ITask)instance);
                }
            }
        }
    

    And here is my class to activate, note that I had to change the constructor params to objects, the only way I could get it to work.

    public class CalculateDowntimeTask : Task
    {
        public CalculateDowntimeTask(object proxy, object context) : 
            base((TaskServiceClient)proxy, (TaskDataDataContext)context) { }
    
        public override void Execute()
        {
            LogMessage(new TaskMessage() { Message = "Testing" });
            BroadcastMessage(new TaskMessage() { Message = "Testing" });
        }
    }
    

提交回复
热议问题