代码之家  ›  专栏  ›  技术社区  ›  Les

如何在仅在基类中实现的继承类中调用Member

  •  1
  • Les  · 技术社区  · 17 年前

    场景是我正在更改“请求”的状态,有时新状态是暂时的,需要立即更改为另一种状态。所以我在基类WorkflowCommandBase中的一个方法中:

        public virtual Request Execute()
        {
            ChangeRequestStatus();
            QueueEmails();
            TrackRequestStatus();
            return ExecuteAutoTransitionStatus(GetTransitionStatus());
        }
    

    private Request ExecuteAutoTransitionStatus(string commandName)
    {
        if (String.IsNullOrEmpty(commandName))
        {
            return Request;
        }
    
        Type calledType = Type.GetType(commandName);
        return (Request)calledType.InvokeMember(
               "Execute",
               BindingFlags.InvokeMethod
                    | BindingFlags.Public | BindingFlags.Instance,
               null,
               null,
               new Object[]
                   {Request, TarsUser, GrantRepository, TrackingRepository});
        }
    

    Class Diagram .

    2 回复  |  直到 7 年前
        1
  •  2
  •   Martin Harris    17 年前

    @马丁:谢谢你的帮助。

    我发布这个,以防它可能对其他人有所帮助。

        private Request ExecuteAutoTransition(Type newStatus)
        {
            // No transition needed
            if (newStatus == null)
            {
                return Request;
            }
    
            // Create an instance of the type
            object o = Activator.CreateInstance(
                newStatus, // type
                new Object[] // constructor parameters
                    {
                        Request,
                        TarsUser,
                        GrantRepository,
                        TrackingRepository
                    });
    
            // Execute status change
            return (Request) newStatus.InvokeMember(
                                 "Execute", // method
                                 BindingFlags.Public 
                                    | BindingFlags.Instance 
                                    | BindingFlags.InvokeMethod, // binding flags
                                 Type.DefaultBinder, // binder
                                 o, // type
                                 null); // method parameters
        }
    
        2
  •  2
  •   Les    17 年前

    如果Execute方法是静态的,并且是在基类上定义的,则需要添加BindingFlags。将层次结构扁平化为绑定标志:

     BindingFlags.InvokeMethod | BindingFlags.Public
     | BindingFlags.Static | BindingFlags.FlatternHierarchy
    

    这似乎是最有可能的问题,因为你说它没有找到方法,但这个标志只有在你搜索静态成员时才有效。

    Activator 类,否则您可能需要创建某种工厂。