2012-11-08 2 views
6

누구나 설명 할 수 있습니까? 이유는 "개인 읽기 전용 Int32 [] _array = new [] {8, 7, 5};" null 일 수 있을지 어떨지초기화 된 읽기 전용 필드가 null 인 이유는 무엇입니까?

이 예에서는 작동하며 _array는 항상 null이 아닙니다. 하지만 내 회사 코드에서 나는 simliar 코드가 있고 _array는 항상 null입니다. 그래서 저는 그것을 정적이라고 선언해야했습니다.

클래스는 내 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로 만든 모든 개체는 null을 갖습니다. 직렬화 콜백을 사용하여 필요한 다른 필드를 초기화 할 수 있습니다. 특히, [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

관련 문제