何時readonly 欄位不是 readonly 的?結果出呼你想象!!!

來源:互聯網
上載者:User
作者:不及格的程式員-八神

 
不要以為只有在建構函式中它們是可以更改的,其實還有其它的狀況。

運行一下下面的代碼你就無語了,介紹了兩種方式,out輸出與聯合體。

 1 using System;
 2 using System.Collections.Generic;
 3 using System.Linq;
 4 using System.Web;
 5 using System.Web.UI;
 6 using System.Web.UI.WebControls;
 7 using System.Runtime.InteropServices;
 8 
 9 namespace Hello_2010
10 {
11     public partial class _Default : System.Web.UI.Page
12     {
13         protected void Page_Load(object sender, EventArgs e)
14         {
15             S3 s3 = new S3();
16             int x = s3.A.X;
17             s3.B.X++; //A.X已經變成1了,不信你看看。。。。
18 
19             S s = new S(42);
20             s.MultiplyInto(10, out s); //變數X變成420了,而不是42。
21 
22             
23         }
24 
25         protected void Button1_Click(object sender, EventArgs e)
26         {
27             //this.Label1.Text = "ok";
28             //this.Label1.Text += this.FileUpload1.FileName;
29         }
30     }
31 
32     struct S 
33     {
34         public readonly int X;
35 
36         public S(int x) { X = x; }
37 
38         public void MultiplyInto(int c, out S target) 
39         {
40             System.Console.WriteLine(this.X);
41             target = new S(X * c);
42             System.Console.WriteLine(this.X); // same? it is, after all, readonly.
43         }
44     }
45 
46 
47     struct S1
48     {
49         public readonly int X;
50     }
51 
52     struct S2
53     {
54         public int X;
55     }
56 
57     [StructLayout(LayoutKind.Explicit)]
58     struct S3
59     {
60         [FieldOffset(0)]
61         public S1 A;
62         [FieldOffset(0)]
63         public S2 B;
64     }
65 }

 

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.