任何人都可以請解釋一下,爲什麼「私人只讀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