如何使用动态调用基类中的受保护方法

时间:2012-12-06 04:08:28

标签: c# c#-4.0 .net-4.5

获得以下代码

 protected virtual void InternalChange(DomainEvent @event)
 {
       ((dynamic) this).Apply(@event);
 }

子对象实现了通过许多字段处理事件的逻辑,例如

 protected Apply ( Message1 message)
 {

 }
protected Apply ( Message2 message)
 {

 }

然而,这给出了一个错误,说它无法访问。我试过虚拟但没有运气..

有什么想法吗?希望没有这种方法的反思。 (例如http://blogs.msdn.com/b/davidebb/archive/2010/01/18/use-c-4-0-dynamic-to-drastically-simplify-your-private-reflection-code.aspx

更多信息我可以将InternalChange移动到子类,但是id而不是让子进行调度。

   void Apply(AggregateRootHandlerThatMeetsConventionEvent domainEvent)
    {
        OnAggregateRootPrivateHandlerThatMeetsConventionCalled = true;
    }


    void Apply(AggregateRootPrivateHandlerThatMeetsConventionEvent domainEvent)
    {
        OnAggregateRootPrivateHandlerThatMeetsConventionCalled = true;
    }

    void Apply(AggregateRootProtectedHandlerThatMeetsConventionEvent domainEvent)
    {
        OnAggregateRootProtectedHandlerThatMeetsConventionCalled = true;
    }


    protected override void InternalChange(DomainEvent @event)
    {

        Apply(((dynamic)@event));
    }

现在编辑我在孩子中使用它(并使其成为父抽象),但是它的丑陋id而非实现者不担心调度。

    protected void Handle(DomainEvent message)
    {
        Handle ( (dynamic) message);
    }

2 个答案:

答案 0 :(得分:0)

例如,您应该定义基类以在方法签名上包含abstractvirtual

protected abstract void Apply(Message1 message);

如果要在基类中定义一个不必(但可以)在子类中重写的实现,请使用virtual

在您的子类中,您将覆盖它:

protected override void Apply(Message1 message)
{
    // code here
}

此外,在您的示例中,方法InternalChange尝试使用Apply类型的参数调用DomainEvent,但是,在Apply的重载中,它们都是接受任意类型的Message1Message2。如果它确实编译了,那么无论如何都会出现运行时错误,因为.NET动态运行时将无法找到与参数匹配的适当方法。

至于使用动态,我认为现在的问题是没有必要的。

答案 1 :(得分:0)

逻辑有点......逆转。我不明白一两件事:什么类调用apply,基类型或子类型?如何识别发送事件的子类?难道你不能渲染Apply虚拟保护并在基类中留空吗?

相关问题