初始化的只读字段为空,为什么?

任何人都可以解释,为什么“私人只读Int32 [] _array = new [] {8,7,5};” 可以为空吗?

在此示例中,它可以工作,_array始终不为null。 但在我的公司代码中,我有一个simliar代码,_array总是为null。 所以我不得不宣布它是静态的。

该类是我的WCF合同中的部分代理类。

using System; using System.ComponentModel; namespace NullProblem { internal class Program { private static void Main(string[] args) { var myClass = new MyClass(); // Null Exception in coperate code int first = myClass.First; // Works int firstStatic = myClass.FirstStatic; } } // My partial implemantation public partial class MyClass { private readonly Int32[] _array = new[] {8, 7, 5}; private static readonly Int32[] _arrayStatic = new[] {8, 7, 5}; public int First { get { return _array[0]; } } public int FirstStatic { get { return _arrayStatic[0]; } } } // from WebService Reference.cs public partial class MyClass : INotifyPropertyChanged { // a lot of Stuff #region Implementation of INotifyPropertyChanged public event PropertyChangedEventHandler PropertyChanged; #endregion } } 

WCF不运行构造函数(包括字段初始值设定项),因此WCF创建的任何对象都将为null。 您可以使用序列化回调来初始化所需的任何其他字段。 特别是, [OnDeserializing]

 [OnDeserializing] private void InitFields(StreamingContext context) { if(_array == null) _array = new[] {8, 7, 5}; } 

我最近也碰到了这个问题。 我有一个带有静态只读变量的非静态类。 它们总是显得null我认为这是一个错误

通过向类添加静态构造函数来修复它:

 public class myClass { private static readonly String MYVARIABLE = "this is not null"; // Add static constructor static myClass() { // No need to add anything here } public myClass() { // Non-static constructor } public static void setString() { // Without defining the static constructor 'MYVARIABLE' would be null! String myString = MYVARIABLE; } }