object reference not set to an instance of an object" - Not "initialized" through WCF?

本文讨论了在使用WCF服务时遇到的对象引用未设置到对象实例的问题,并提供了解决方案,即通过OnDeserializing回调进行对象初始化。

object reference not set to an instance of an object" - Not "initialized" through WCF?

  • Harry Pfleger Users MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals Wednesday, February 20, 2008 8:55 PM
    Helpful Votes0 votes Vote As Helpful

    Could one please give me a hit, or probably confirm a bug?

     

    I have a custom class, something like this:

     

    [DataContract]

    public class CompositeType

    {

       ClassX x = new ClassX();

       [DataMember]

       public string Field

       {

          get { return x.X; }

          set { x.X = value; }

       }

    }

     

    public class ClassX

    {

       public string X;

    }

     

     

    When used in a WCF service, I get a "object reference not set to an instance of an object". I have also tried using a class initializer (public CompositeType()), where I do the new ClassX(); but I do get the same result...

    Does anyone know why? Is there a solution for it?

     

    Thankx, Cheers Harry

Answers

  • Carlos FigueiraMSFTUsers MedalsUsers MedalsUsers MedalsUsers MedalsUsers Medals Wednesday, February 20, 2008 10:41 PM
    Helpful Votes0 votes Vote As Helpful
    Answer

    On deserialization, WCF does not call the constructors or field initializers of the type it's creating. If you need to perform some initialization on deserialization, you need to use the OnDeserializing callback (http://msdn2.microsoft.com/en-us/library/system.runtime.serialization.ondeserializingattribute.aspx). The example below should work for you:

     

    [DataContract]

    public class CompositeType

    {

        ClassX x;

        [DataMember]

        public string Field

        {

            get { return x.X; }

            set { x.X = value; }

        }

        public CompositeType()

        {

            Initialize();

        }

        [OnDeserializing]

        public void OnDeserializing(StreamingContext ctx)

        {

            Initialize();

        }

        private void Initialize()

        {

            this.x = new ClassX();

        }

    }

    public class ClassX

    {

        public string X;

    }

### C# 中 "Object reference not set to an instance of an object" 错误解析 当遇到 `System.NullReferenceException` 异常提示 “Object reference not set to an instance of an object” 时,意味着程序试图访问一个尚未初始化的对象引用[^1]。 #### 解决方案概述 为了有效处理此类异常,可以采取以下几种策略: #### 方法验证与对象实例化检查 确保所有被调用的方法所属对象都已被正确定义和实例化。对于可能为空的情况,在执行任何成员访问之前应先进行 null 检查: ```csharp if (myObject != null) { myObject.DoSomething(); } else { Console.WriteLine("The object is not initialized."); } ``` #### 使用可空类型与默认值设定 针对允许为 null 的字段或属性,考虑采用可空类型(`?`)来声明它们,并设置合理的默认值以减少意外情况的发生。例如,在定义类结构时就可以这样做[^3]: ```csharp public class ResponseMessage { public int code { get; set; } public string? Message { get; set; } = ""; public object? Data { get; set; } = new object(); } ``` #### Unity 特定场景下的组件绑定确认 特别是在 Unity 开发环境中,如果涉及到 UI 组件的操作,则需特别注意脚本中的公共变量是否已经正确指定了相应的游戏对象或组件。这一步骤往往容易被忽视而导致 NullReferenceException 发生[^4]。 - **案例说明**: 当向 Canvas 添加 Button 并为其编写事件处理器后,还需通过 Inspector 将该按钮实际分配给脚本里的相应字段。 ![Unity Component Assignment](https://example.com/image.png) #### 安全导航运算符的应用 利用 C# 提供的安全导航运算子 (`?.`) 来简化对潜在 null 对象链的判断逻辑,从而避免显式的多重嵌套条件语句: ```csharp var messageLength = responseMessage?.Message?.Length ?? 0; // 如果responseMessage 或者 Message 是null, 则messageLength会被赋值为0. ``` ---
评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值