c# – 此Struct类型的定义有什么问题

前端之家收集整理的这篇文章主要介绍了c# – 此Struct类型的定义有什么问题前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我已经定义了这样的结构:
  1. struct Test
  2. {
  3. private string assayName;
  4. public string AssayName { get; set; }
  5.  
  6. private string oldUnitName;
  7. public string OldUnitName { get; set; }
  8.  
  9. private string newUnitName;
  10. public string NewUnitName { get; set; }
  11.  
  12. public Test(string name,string oldValue,string newValue)
  13. {
  14. assayName = name;
  15. oldUnitName = oldValue;
  16. newUnitName = newValue;
  17. }
  18.  
  19. }

但它给了我以下错误

“Error 13 Backing field for automatically implemented property
‘EnterResults.frmApplication.Test.NewUnitName’ must be fully assigned
before control is returned to the caller. Consider calling the default
constructor from a constructor initializer.”

解决方法

嗯,真的有两个问题:

1.您使用自动属性,但随后也提供字段,两者之间没有布线.

2.当您使用自动属性时,因为这是一个结构,所以必须先对它们进行初始化.您可以通过调用默认构造函数来完成此操作.所以修改后的版本是:

  1. struct Test
  2. {
  3. public Test(string name,string newValue)
  4. : this()
  5. {
  6. AssayName = name;
  7. OldUnitName = oldValue;
  8. NewUnitName = newValue;
  9. }
  10.  
  11. public string AssayName { get; private set; }
  12. public string OldUnitValue { get; private set; }
  13. public string NewUnitValue { get; private set; }
  14. }

猜你在找的C#相关文章