开发者

C# .NET: Is it possible to create compile time warnings when property is set to invalid values?

开发者 https://www.devze.com 2022-12-21 19:34 出处:网络
This is just a feasibility question.I know that if I say int myInt = \"5\"; I get a compile time error.What I want to do is create compile time errors or warnings on objec开发者_高级运维ts. So le

This is just a feasibility question. I know that if I say

   int myInt = "5"; 

I get a compile time error. What I want to do is create compile time errors or warnings on objec开发者_高级运维ts. So let's say I have a custom object with a few properties. One of the properties cannot be null otherwise the solution will not compile:

   public static class NoNullObjects
   {
       //NotNullable
       public static NotNullObject {get; set;}
   }

MyClass.cs:

   Line#55   NoNullObjects.NotNullObject = null;

When I build I want to see:

   Error: NotNullObject cannot be set to null. MyClass.cs Line 55.

Is there a way to do this?


No, not with just C#. Microsoft's Code Contracts work may give you what you want: http://msdn.microsoft.com/en-us/devlabs/dd491992.aspx.


Here is a question that covers the same topic. The accepted answer suggests that you use code contracts.

0

精彩评论

暂无评论...
验证码 换一张
取 消