在结构体中使用自动属性时的提示

C# 3.0引入了“自动属性”,写起代码方便了许多。但当在结构体(struct)中使用自动属性时,有一个很细小的问题要注意,这就是,带参构造器(非默认构造器)中不能为属性赋值。

请看下面的代码:

 1 using  System;
 2
 3 class  A
 4 {
 5  static void Main()
 6  {
 7  }

 8}

 9
10 struct  T
11 {
12  public int P getset; }
13
14  public T(int p) this.P = p; }
15}

注意class A没有用途,只是能方便编译而已;主要关注struct T。

编译这段代码,将得到如下错误消息:

a.txt(14,21): error CS0188: The 'this' object cannot be used before all of its fields are assigned to
a.txt(14,10): error CS0843: Backing field for automatically implemented property 'T.P' must be fully assigned before control is returned to the caller. Consider calling the default constructor from a constructor initializer.

错误消息告诉我们,自动属性背后的字段还没有初始化;并且给了我们一个建议,那就是在构造器之前调用默认构造器。

因此,将构造器的定义改为 public T(int p) : this() { this.P = p; } 即可修正该错误。

但是,如果定义的是class T,而不是struct,则不会出现上述错误。各种原因尚不理解。
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值