本文介绍了初始化只读字段为空,为什么?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

任何人都可以请解释一下,为什么私人只读的Int32 [] = _array新[] {8,7,5};可以为空?



在这个例子中,它的工作原理,并_array始终不为空。但在我的企业法人代码我有这类似于代码和_array总是空。于是,我不得不宣布它为static。



类是部分代理类从我的WCF合同。

 使用系统; 
使用System.ComponentModel;

命名空间NullProblem
{
内部类节目
{
私有静态无效的主要(字串[] args)
{
VAR MyClass的=新MyClass的();

//空异常在我携手代码
INT第一= myClass.First;
//作品
INT firstStatic = myClass.FirstStatic;
}
}

//我的部​​分implemantation
公共部分类MyClass的
{
私人只读的Int32 [] = _array新[] {8,7,5};
私人静态只读的Int32 [] = _arrayStatic新[] {8,7,5};

公众诠释一是
{
{返回_array [0]; }
}

公众诠释FirstStatic
{
{返回_arrayStatic [0]; }
}
}

//从WebService的Reference.cs
公共部分MyClass类:INotifyPropertyChanged的
{
//很多东西
$ b $ INotifyPropertyChanged的

公共事件PropertyChangedEventHandler的PropertyChanged乙#地区的实施情况;

#endregion
}

}


解决方案

WCF不运行构造(包括外地初始化),因此通过WCF创建的任何对象将有一个空。您可以使用序列化回调初始化你需要的任何其他领域。尤其是, [OnDeserializing]

  [OnDeserializing] 
私人无效InitFields(的StreamingContext上下文)
{
如果(_array == NULL)_array =新[] {8,7,5};
}


Can anyone please explain, why "private readonly Int32[] _array = new[] {8, 7, 5};" can be null?

In this example, it works, and _array is always not null. But in my corporate code I have a simliar code and _array is always null. So I forced to declared it as static.

The Class is a partial Proxy Class from my WCF Contract.

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
    }

}
解决方案

WCF does not run the constructor (which includes the field initializer), so any objects created by WCF will have that null. You can use a serialization callback to initialize any other fields you need. In particular, [OnDeserializing]:

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

这篇关于初始化只读字段为空,为什么?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-29 17:06
查看更多