在委托中使用'base'关键字会导致System.BadImageFormatException [英] Using 'base' keyword in delegate causes System.BadImageFormatException
问题描述
我有一个奇怪的问题,我想如果有人可以启发我为什么这是发生。我在基本抽象类中有一个受保护的方法如下:
I have a weird problem and I would like if someone can enlighten me on why is this happening. I have a protected method in a base abstract class as following:
protected T ForExistingEntity<T>(TEntity entity, object key, Func<Entity, T> action) {
entity = GetByKey(key);
if (entity != null)
return action(entity);
return default(T);
}
我继承的类的原始调用如下:
My original call from an inherited class was as follows:
return base.ForExistingEntity(
new MyEntity(), key, e => {
e.someFiled = 5;
return base.Update(e);
}
);
当此代码执行时,会在以下行中引发异常:
When this code executes, an exception get raised at the line that reads:
return action(entity);
。异常为:
System.BadImageFormatException:尝试加载格式不正确的程序。 (来自HRESULT的异常:0x8007000B)
System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
现在,当我按如下方式修改调用时:
Now when I modify my call as following:
return base.ForExistingEntity(
new MyEntity(), key, e => {
e.someFiled = 5;
return Update(e);
}
);
它没有任何问题正常运行。
it runs normally without any issues.
修改:
Update方法位于基本抽象类中,如下所示:
The Update method is located in the base abstract class and looks like this:
public virtual bool Update(TEntity entity) {
Condition.Requires(entity, "entity")
.IsNotNull();
if (ValidateEntity(entity))
return Update(entity, true);
return false;
}
我开始认为这是因为Update是虚拟的调用实际上是源自基类本身?
I am starting to think that this is happening because of Update being virtual and the call actually originates in the base class itself? The exception isn't very helpfull anyway.
推荐答案
这似乎是一个已知的C#编译器错误涉及从泛型中的匿名方法调用基本虚拟方法类。如果你想解决,不要犹豫,upvote这个bug连接。幸运的是,这里的解决方法很简单。
This seems to be a known C# compiler bug involving calling a base virtual method from an anonymous method within a generic class. Don't hesitate to upvote this bug on connect if you want it solved. Fortunately, the workaround is quite simple here.
这篇关于在委托中使用'base'关键字会导致System.BadImageFormatException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!