我试图通过(this as dynamic).When(e)
从我的基类动态调用我父项的方法,但是我收到有关保护级别的错误:
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
课程是公开的,将Person.When(PersonCreated)
更改为公开会产生新的错误The best overloaded method match for 'Person.When(PersonCreated)' has some invalid arguments
...
我想要实现的是通过基础When(e)
方法将事件“路由”到父类的Apply(e)
方法。
理想情况下,基础中的When
方法不应公开。
我拉我的头发毫无疑问做了一些非常愚蠢的事情......任何想法请或者我需要使用反射吗?
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");
}
答案 0 :(得分:2)
请注意,在public
方法When()
时,您会收到其他异常。即它现在可以访问,但你没有传递正确的类型。
声明的PersonCreated
方法需要 DomainEvent
的实例。但是您的呼叫站点仅传递dynamic
的实例。
通常,DomainEvent
遵循通常在编译时完成的运行时行为。但除此之外,你必须遵循相同的规则。由于编译器无法保证PersonCreated
是DomainEvent
的实例,因此会出现错误(或者更具体地说,(this as dynamic).When(e as dynamic);
与方法的已知重载不匹配。)< / p>
您应该可以通过这样调用来获取代码:
e
即。让运行时绑定基于动态类型getline
而不是静态类型。