由于其保护级别,从基础动态调用 parent 方法失败并无法访问

Calling parent method dynamically from base fails with inaccessible due to its protection level

我正在尝试通过 (this as dynamic).When(e) 从我的基础 class 动态调用我的 parent 上的方法,但我收到有关保护级别的错误:

An unhandled exception of type 'Microsoft.CSharp.RuntimeBinder.RuntimeBinderException' occurred in System.Core.dll

Additional information: 'Person.When(PersonCreated)' is inaccessible due to its protection level

Person class 是 public,将 Person.When(PersonCreated) 更改为 public 会出现新错误 The best overloaded method match for 'Person.When(PersonCreated)' has some invalid arguments...

我想要实现的是通过基本 Apply(e) 方法将 'route' 事件发送到 parent class 的 When(e) 方法。

理想情况下,基础中的 When 方法不应是 public。

毫无疑问,我正在拔头发做一些非常愚蠢的事情...请提供任何想法,或者我是否需要改用反射?

public abstract class EventSourcedAggregate
{
    readonly List<DomainEvent> mutatingEvents = new List<DomainEvent>();
    public readonly int UnmutatedVersion;

    protected void Apply(DomainEvent e)
    {
        this.mutatingEvents.Add(e);

        // the below line throws inaccessible protection level
        (this as dynamic).When(e);
    }
}

public abstract class DomainEvent
{
    // snipped some time stamp stuff not relevant here
}

public class PersonCreated : DomainEvent
{
    public readonly string Name;
    public readonly string Address;

    public PersonCreated(string name, string address)
    {
        Name = name;
        Address = address;
    }
}

public class Person : EventSourcedAggregate
{
    public Person(string name, string address)
    {
        Apply(new PersonCreated(name, address));
    }

    public string Name { get; private set; }
    public string Address { get; private set; }

    void When(PersonCreated e)
    {
        Name = e.Name;
        Address = e.Address;
    }
}

static void Main(string[] args)
{
    var user = new Person("sir button", "abc street");
}

请注意,当 When() 方法执行 public 时,您会得到一个不同的异常。 IE。它现在可以访问,但您没有传递正确的类型。

声明的 When() 方法 需要 PersonCreated 的实例。但是您的呼叫站点仅传递 DomainEvent.

的实例

一般来说,dynamic 遵循通常在编译时完成的运行时行为。但除此之外,您必须遵循相同的规则。由于编译器不能保证 DomainEventPersonCreated 的实例,您会得到错误(或者更具体地说,DomainEvent 与方法的已知重载不匹配)。

您应该可以通过这样调用来使代码工作:

(this as dynamic).When(e as dynamic);

即让运行时基于 e 的动态类型而不是其静态类型进行绑定。