如何使用代码协定在C#中声明编译时间?

sha*_*oth 5 c# static-assert code-contracts

根据此答案, C#现在具有“代码约定”,该代码约定应该可用,而不是C ++编译时断言。现在我有了这个魔术代码:

IntPtr pointer;
//blahblahblah
pointer = new IntPtr(pointer.ToInt32() + Marshal.SizeOf(typeof(SomeStruct)));
Run Code Online (Sandbox Code Playgroud)

需要IntPtr是相同大小的Int32。所以我想要一个编译时间断言-像这样的C ++代码

static_assert(sizeof(IntPtr)==sizeof(Int32))
Run Code Online (Sandbox Code Playgroud)

所以我尝试了以下方法:

System.Diagnostics.Contracts.Contract.Assert(false); //just to test it
pointer = new IntPtr(pointer.ToInt32() + Marshal.SizeOf(typeof(SomeStruct)));
Run Code Online (Sandbox Code Playgroud)

false进入Assert()以便它肯定会失败,但是编译通过就可以了。

那么,如何使用代码协定来声明编译时间呢?

Eti*_*heu 2

这是因为代码契约与编译时断言不同。它们仍然是运行时代码,但它们还附带静态分析规则集,您可以在项目中启用该规则集来执行您想要的操作。

看看这个问题,它看起来已经很好地回答了这个问题:Contract.Assert do not throw compiling error