C#:struct的陷阱:無法修改“xxx”的返回值,因為它不是變量


示例代碼如下:

 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

 


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

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


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM