Disable/suppress warning CS0649 in C# for a specific field of class

元气小坏坏 提交于 2019-11-30 08:54:08

问题


I have some fields in a C# class which I initialize using reflection. The compiler shows CS0649 warning for them:

Field foo' is never assigned to, and will always have its default valuenull' (CS0649) (Assembly-CSharp)

I'd like to disable the warning for these specific fields only and still let the warning be shown for other classes and other fields of this class. It is possible to disable CS0649 for the whole project, is there anything more fine-grained?


回答1:


You could use #pragma warning to disable and then re-enable particular warnings:

public class MyClass
{
    #pragma warning disable 0649

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

    #pragma warning restore 0649

    // rest of class
}

Refer to Suppressing “is never used” and “is never assigned to” warnings in C# for an expanded answer.




回答2:


I believe it's worth noting the warning can also be suppressed by using a field initializer. This clutters your code much less.

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

    // rest of class
}



回答3:


//disable warning here
#pragma warning disable 0649

 //foo field declaration

//restore warning to previous state after
#pragma warning restore 0649



回答4:


public class YouClass
{
#pragma warning disable 649
    string foo;
#pragma warning restore 649
}



回答5:


If you want to disable ALL warnings in the project (rather than per script) then do this:

Ceate a text file called mcs.rsp (for editor scripts) in your YOUR_PROJECT_NAME/Assets directory with contents (for example):

-nowarn:0649

(You can change the number to match whatever warning you want)

Original answer

Note: This doesn't disable the warnings in the Unity console if you are using Unity (I am still investigating how to remove those)

Here is some Unity documentation with more information



来源:https://stackoverflow.com/questions/13726743/disable-suppress-warning-cs0649-in-c-sharp-for-a-specific-field-of-class

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!