这是代码契约重写器中的错误吗?
我正在尝试 .NET 代码契约。当运行时契约检查关闭时,以下代码运行良好,但当运行时契约检查打开时失败:
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace ConsoleApplication1
{
public class Item<T> where T : class { }
public class FooItem : Item<FooItem> { }
[ContractClass(typeof(ITaskContract<>))]
public interface ITask<T> where T : Item<T>
{
void Execute(IEnumerable<T> items);
}
[ContractClassFor(typeof(ITask<>))]
internal abstract class ITaskContract<T> : ITask<T> where T : Item<T>
{
void ITask<T>.Execute(IEnumerable<T> items)
{
Contract.Requires(items != null);
Contract.Requires(Contract.ForAll(items, x => x != null));
}
}
public class FooTask : ITask<FooItem>
{
public void Execute(IEnumerable<FooItem> items) { }
}
class Program
{
static void Main(string[] args)
{
new FooTask();
}
}
}
运行此代码时出现的错误不是契约违反。相反,重写器似乎以某种方式生成了损坏的二进制文件:
未处理的异常:System.BadImageFormatException:尝试加载格式不正确的程序。 (HRESULT 异常:0x8007000B) 在 ConsoleApplication1.Program.Main(String[] args)
如果删除以下行,错误就会消失:
Contract.Requires(Contract.ForAll(items, x => x != null));
我做错了什么,还是这是二进制重写器中的错误?我能做什么呢?
I am experimenting with .NET Code Contracts. The following code runs just fine when runtime contract checking is turned off, but fails when runtime contract checking is turned on:
using System.Collections.Generic;
using System.Diagnostics.Contracts;
namespace ConsoleApplication1
{
public class Item<T> where T : class { }
public class FooItem : Item<FooItem> { }
[ContractClass(typeof(ITaskContract<>))]
public interface ITask<T> where T : Item<T>
{
void Execute(IEnumerable<T> items);
}
[ContractClassFor(typeof(ITask<>))]
internal abstract class ITaskContract<T> : ITask<T> where T : Item<T>
{
void ITask<T>.Execute(IEnumerable<T> items)
{
Contract.Requires(items != null);
Contract.Requires(Contract.ForAll(items, x => x != null));
}
}
public class FooTask : ITask<FooItem>
{
public void Execute(IEnumerable<FooItem> items) { }
}
class Program
{
static void Main(string[] args)
{
new FooTask();
}
}
}
The error I get when running this code is not a contract violation. Rather, it looks like the rewriter is somehow generating a corrupted binary:
Unhandled Exception: System.BadImageFormatException: An attempt was made to load a program with an incorrect format. (Exception from HRESULT: 0x8007000B)
at ConsoleApplication1.Program.Main(String[] args)
The error goes away if I remove the following line:
Contract.Requires(Contract.ForAll(items, x => x != null));
Am I doing something wrong, or is this a bug in the binary rewriter? What can I do about it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是重写器中已确认的错误:
http://social.msdn.microsoft.com/Forums/en-US/codecontracts/thread/66410714-4475-45fb-b0db-50036463029e
It's a confirmed bug in the rewriter:
http://social.msdn.microsoft.com/Forums/en-US/codecontracts/thread/66410714-4475-45fb-b0db-50036463029e