Is this a bug in the Code Contracts rewriter?

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?


It's a confirmed bug in the rewriter:

http://social.msdn.microsoft.com/Forums/en-US/codecontracts/thread/66410714-4475-45fb-b0db-50036463029e

链接地址: http://www.djcxy.com/p/23736.html

上一篇: CodeContracts问题

下一篇: 这是代码合同重写器中的错误吗?