C# - Struct doest not allow redifinition of the parameterless constructor

本文深入探讨了C#中结构体的使用,特别是构造函数和默认构造函数的功能与实现。解释了为什么结构体不能为空,并如何通过调用默认构造函数来解决此类问题。

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

If you are familiar with the C# construct structure, than you may probably be familiar with the structure, while structure will group the members in continous memory, and it is more lightweight than classses and believes to create less fragment than the class (reference types).

    private struct CPSSOWDeleteTuple
    {
      public CPSMessage Data { get; set; }
      public CPSMessage Schema { get; set; }

      public CPSSOWDeleteTuple(CPSMessage data, CPSMessage schema) 
      {
        Data = data;
        Schema = schema;
      }
 

There is somthing that you may not be very clear about the structure types. for one thing, since a struct cann not be empty, so the compiler will generate a default constructor so it can fit in many application situation such as the List<struct> or Map<...,struct>;

 

 

Let 's see one example, suppose we have a struct which is called CPSSOWDeleteTuple, and this tuple has two member, one represents a Data and the other represents a schema, and both the Data and the Schema are of the type of "CPSMessage";

 

 

 

   private struct CPSSOWDeleteTuple
    {
      public CPSMessage Data { get; set; }
      public CPSMessage Schema { get; set; }
   }
 

 

now, we want to provide some constructor which is not an void paramters list. if you directly do this: 

 

    private struct CPSSOWDeleteTuple
    {
      //... same as before

      public CPSSOWDeleteTuple(CPSMessage data, CPSMessage schema) 
      {
        Data = data;
        Schema = schema;
      }
   }

 

 

you will get an error, basically it will say that "Backing field for autmatically implemented property '...Data' Must be fully initialized before control is returned to the caller. Consider calling the default constructor from a constructor initializer"....

 

it does not make much sense, but I do know somewhere to make clean of this error: here ist the modified version of the CPSSOWDeleteTuple.

 

public CPSSOWDeleteTuple(CPSMessage data, CPSMessage schema) : this()
      {
        Data = data;
        Schema = schema;
      }

 

As you can see, you have to call the parameterless constructor in another constructor, then the compiler will stop complaining...

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值