從程式結果分析對象上轉型

來源:互聯網
上載者:User

//person.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class person
    {
        public int Age = 24;
        public String Name = "cheng.cheng";
    }
}
//Program.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace ConsoleApplication1
{
    class Program
    {
        private int TestA = 0;
        static void Main(string[] args)
        {
            Console.WriteLine("Int:");
            int a = 1;
            object objectA = (Object)a;
            a = 2;
            Console.WriteLine("a=" + a + ",objectA=" + objectA);
            Console.ReadLine();
            Console.WriteLine("String:");
            string strA = "abc";
            object objectStra = (Object)strA;
            strA = "abcdefg";
            Console.WriteLine("strA=" + strA + ",objectStra=" + objectStra);
            Console.ReadLine();
            Console.WriteLine("Object:");
            object objecta1 = "123";
            string stra1 = (string)objecta1;
            objecta1 = "123456";
            Console.WriteLine("stra1=" + stra1 + ",objecta1=" + objecta1);
            Console.ReadLine();

            Console.WriteLine("Class:");
            person p = new person();
            Object objectP = p;
            person pp = (person)objectP;
            p.Age = 20;
            p.Name = "LiMing";
            Console.WriteLine("p.Age=" + p.Age + ",objectP.Age=" + pp.Age);
            Console.WriteLine("p.Name=" + p.Name + ",objectP.Name=" + pp.Name);
            Console.ReadLine();

            Program Program = new Program();
            Console.WriteLine(Program.TestA);
            Console.ReadLine();

        }
    }
}

輸出結果:

Int:
a=2,objectA=1

String:
strA=abcdefg,objectStra=abc

Object:
stra1=123,objecta1=123456

Class:
p.Age=20,objectP.Age=20
p.Name=LiMing,objectP.Name=LiMing

 

說明:

1、上轉型時對於實值型別和String Object是要重新分配空間的。

2、對於Calss對象則是引用地址。

3、上轉型是一種特殊的賦值,由此推論到任意賦值遵守1、2兩條。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.