任何人都可以请解释一下,为什么“私人只读Int32 [] _array = new [] {8,7,5};”可以为null?初始化只读字段为空,为什么?
在这个例子中,它有效,并且_array总是不为空。但在我的公司代码中,我有一个simliar代码,_array总是空。所以我不得不声明它是静态的。
该类是我的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
}
}
这是没有多大用处向我们展示的作品代码,并说还有一些其他的代码不起作用。你需要给我们一个简短但完整的例子,它不起作用。 –
如果它在这里而不是在你的代码中工作,很明显你的代码有问题。除非您发布,否则我很难提供任何帮助。 – Gorpik
在我的LINQPad中按照预期工作。 – Davio