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

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

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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;

    }

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值