Conditional Attribute Exception with Code Contracts

I'm getting an exception when I use code contracts on the following code:

public void Debug(
            dynamic message1, 
            dynamic message2 = null, 
            dynamic message3 = null, 
            dynamic message4 = null, 
            dynamic message5 = null, 
            dynamic message6 = null)
     {
         Contract.Requires(message1 != null, 
             "First Logged Message cannot be null");
     }

I'm trying to configure the project settings so that the checks are done at run time.

The exception is "Cannot dynamically invoke method 'Requires' because it has a Conditional attribute". I've re-read the Code Contracts documentation a couple of times and done some searches, but I do not understand where the conditional attribute is coming from.


The conditional attribute on the Requires method is Conditional("CONTRACTS_FULL") . When you build with contracts turned on, the CONTRACTS_FULL symbol is passed to the compiler. I assume the reason you can't use dynamic dispatch with conditional methods, is because they're compiled during runtime, and the runtime has no way of passing these symbols to the compiler. (Just a guess).

You can probably solve it really easy by assigning message1 to a local (non-dynamic) variable, perhaps an object.

     object m1 = message1;
     Contract.Requires(m1 != null, "First Logged Message cannot be null");

我遇到同样的问题,而不是创建一个变量赋值我可以将动态转换为requires条件参数中的对象。

dynamic message1;
Contract.Requires((object)message1 != null,"First Logged Message cannot be null"); 
链接地址: http://www.djcxy.com/p/59598.html

上一篇: 代码合同,空检查和值/参考类型

下一篇: 有代码合同的条件属性例外