示例代码如下:

 public struct SpiderResult
    {        
        public string robotName;
        public string RobotName
        {
            get { return robotName; }
            set { robotName = value; }
        }
        public int num;
        public int totalNum;
    }
    public class TestClass
    {
        public SpiderResult spider = new SpiderResult();
        public SpiderResult Spider 
        {
            get { return spider; }
            set { spider = value; }
        }
    }

调用如下:

public partial class Form1 : Form
    {  
        public Form1()
        {
            TestClass testclass = new TestClass();
            testclass.Spider.RobotName = "Baidu";//编译出错
        }
}

//编译错误

错误 CS1612: 无法修改“SpiderAnalysis.TestClass.Spider”的返回值,因为它不是变量

解决方法:

方法一:

把struct替换成class

方法二:

如果非要用struct不可的话,需重新生成一个所用到的struct,即设置一个中间变量:

public partial class Form1 : Form
{
    public Form1()
    {
        TestClass testclass = new TestClass();
        SpiderResult tempSpider = new SpiderResult();
        tempSpider.robotName = "Baidu";
        testclass.Spider = tempSpider;
    }
}    

参考文章:

http://blog.csdn.net/onlyou930/article/details/5568319

MSDN: Compiler Error CS1612 (编译器错误 CS1612 (C#) ) 
看一下就知道了,中文的比英文原版的逊多了 
C# - Struct in a class.. can not access properties of the struct 
延伸阅读: 
CLR Generics Limitation - Modifying Values In Situ In a Container
 
C#: List of struct
C#:struct的陷阱:无法修改“xxx”的返回值,因为它不是变量C#:struct的陷阱:无法修改“xxx”的返回值,因为它不是变量

 


作者:曾是土木人http://www.cnblogs.com/hongfei

原文地址:http://www.cnblogs.com/hongfei/p/3577052.html

相关文章:

  • 2021-12-08
  • 2022-02-16
  • 2021-07-20
  • 2022-12-23
  • 2021-08-18
  • 2022-12-23
  • 2021-09-06
  • 2021-09-28
猜你喜欢
  • 2022-12-23
  • 2022-12-23
  • 2021-10-12
  • 2021-09-24
  • 2021-10-16
  • 2021-10-30
相关资源
相似解决方案