C#.net:是否有可能创建时属性设置为无效值编译时的警告?

问题描述:

这仅仅是一个可行性的问题。我知道,如果我说

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 objects. 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:

MyClass.cs:

   Line#55   NoNullObjects.NotNullObject = null;

当我建立我想看看:

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



有没有办法做到这一点?

Is there a way to do this?

没有,不只有C#。微软的代码契约的工作可能会给你想要的东西: http://msdn.microsoft。 COM / EN-US / devlabs / dd491992.aspx

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.