2012-11-08 122 views
6

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

} 
+4

這是沒有多大用處向我們展示的作品代碼,並說還有一些其他的代碼不起作用。你需要給我們一個簡短但完整的例子,它不起作用。 –

+2

如果它在這裏而不是在你的代碼中工作,很明顯你的代碼有問題。除非您發佈,否則我很難提供任何幫助。 – Gorpik

+0

在我的LINQPad中按照預期工作。 – Davio

回答

10

WCF不運行構造(包括外地初始化),因此通過WCF創建的任何對象將有一個空。您可以使用序列化回調來初始化您需要的任何其他字段。特別是,[OnDeserializing]

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

只讀字段可以在這樣的構造函數之外分配嗎? –

+0

@Louis不是沒有作弊,沒有。 「readlonly」將不得不被刪除 –

+0

作弊手段反射?還是有一些可以使用的特殊屬性? –

1

我最近也遇到過這個問題。我也有一個非靜態類,只有靜態只讀變量。他們總是出現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; 
    } 
} 
+0

我會考慮這個傢伙在報告任何錯誤之前的答案:http://stackoverflow.com/questions/34259304/static-property-is-null-after-being-assigned/34260123?noredirect=1 – Matt