2012-12-05 74 views
28

我有一些C#類中的字段,我使用反射進行初始化。編譯器顯示了他們CS0649警告:禁用/禁止C#中的特定字段的CS0649

foo' is never assigned to, and will always have its default value空」(CS0649)(彙編CSHARP)

我想禁用警告僅適用於以下具體領域,仍然讓警告可以顯示其他課程和該課程的其他領域。 可以在整個項目中禁用CS0649,還有什麼更精細的?

回答

51

你可以使用#pragma warning禁用,然後重新啓用特定的警告:

public class MyClass 
{ 
    #pragma warning disable 0649 

    // field declarations for which to disable warning 
    private object foo; 

    #pragma warning restore 0649 

    // rest of class 
} 

參考Suppressing 「is never used」 and 「is never assigned to」 warnings in C#一個擴大的答案。

+1

是不是所需的前導零? – SeToY

+0

@SeToY:感謝您的注意;固定。 – Douglas

+0

@SeToY:其實,不,他們不是必需的。 – Douglas

6
//disable warning here 
#pragma warning disable 0649 

//foo field declaration 

//restore warning to previous state after 
#pragma warning restore 0649 
3
public class YouClass 
{ 
#pragma warning disable 649 
    string foo; 
#pragma warning restore 649 
} 
+0

你的回答給5分鐘前還沒有發佈的問題解決方案增加了什麼? – SeToY

+3

他可能只是沒有看到第一個答案。不管怎麼說,還是要謝謝你:) – iseeall

4

我相信這是值得一提的警告,也可以通過使用一個字段初始抑制。這會讓代碼更加混亂。

public class MyClass 
{ 
    // field declarations for which to disable warning 
    private object foo = null; 

    // rest of class 
}