如果您忘记初始化私有或内部的只读成员,或者声明它的类是内部的,那么C#编译器就足以为您提供"永远不会分配字段"警告.但如果该类是公开的,并且只读成员是公共的,受保护的或内部保护的,那么就没有警告!
有谁知道为什么?
示例代码,用于说明发出警告的条件以及未发出警告的条件:
namespace Test1
{
class Test1
{
#if TRY_IT
public readonly int m; //OK: warning CS0649: Field is never assigned to, and will always have its default value 0
protected readonly int n; //OK: warning CS0649: Field is never assigned to, and will always have its default value 0
internal readonly int o; //OK: warning CS0649: Field is never assigned to, and will always have its default value 0
private readonly int p; //OK: warning CS0649: Field is …Run Code Online (Sandbox Code Playgroud)