2012-11-08 77 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