gpt4 book ai didi

c# - 初始化的readonly字段为null,为什么?

转载 作者:太空狗 更新时间:2023-10-29 20:05:26 26 4
gpt4 key购买 nike

谁能解释一下,为什么 private readonly Int32[] _array = new[] {8, 7, 5}; 可以是 null

在这个例子中,它起作用了,而且 _array 总是不是 null。但在我的公司代码中,我有一个类似的代码,_array 始终为 null。所以我被迫将其声明为静态。

该类是我的 WCF 契约(Contract)中的部分代理类。

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 创建的任何对象都将具有该空值。您可以使用序列化回调来初始化您需要的任何其他字段。特别是,[OnDeserializing]:

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

关于c# - 初始化的readonly字段为null,为什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13291428/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com