C# object类型

2019-09-30  本文已影响0人  柒轩轩轩轩
public class Stack
{
  int position;
  object[] data = new object[10];
  public void Push(object obj) {data[position++] = obj;}
  public object Pop() {return data[-- position];}
}

Stack stack = new Stack();
stack.Push("sausage");
string s = (string) stack.Pop(); //Downcast, so explicit is needed

Console.WriteLine(s); //sausage
装箱
int x = 9;
object obj =x; //Box the int
拆箱

拆箱正好相反,把那个对象转化为原来的值类型

int y = (int)obj;  // unbox the int

装箱会把值类型的实例复制到一个新的对象
拆箱会把这个对象的内容再复制给一个值类型的实例

int i = 3;
object boxed = i;
i = 5;
Console.WriteLine(boxed); //3

GetType 方法与typeof操作符

  1. 在实例上调用GetType()方法;
  2. 在类型名上使用typeof操作符
System.Type

System.type 的属性有: 类型的名称, Assembly,基类等

using System;
public class Point {public int X, Y; }
class Test
{
  static void Main()
  {
    Point p = new Point();
    Console.WriteLine(p.GetTpye().Name); // Point
    Console.WriteLine(typeof(Point).Name); // Point
    Console.WriteLine(p.GetType() == typeof(Point); //true
    Console.WriteLine(p.X.GetType().Name); //Int32
    Console.WriteLine(p.Y.GetType().FullName); //System.Int32
  }
}

ToString()

int x = 1;
string s = x.ToString(); //s is "1"
public class Stack
{
  int position;
  object[] data = new object[10];
  public void Push(object obj) {data[position++] = obj;}
  public object Pop() {return data[-- position];}
}

Stack stack = new Stack();
stack.Push("sausage");
string s = (string) stack.Pop(); //Downcast, so explicit is needed

Console.WriteLine(s); //sausage
装箱
int x = 9;
object obj =x; //Box the int
拆箱

拆箱正好相反,把那个对象转化为原来的值类型

int y = (int)obj;  // unbox the int

装箱会把值类型的实例复制到一个新的对象
拆箱会把这个对象的内容再复制给一个值类型的实例

int i = 3;
object boxed = i;
i = 5;
Console.WriteLine(boxed); //3

GetType 方法与typeof操作符

  1. 在实例上调用GetType()方法;
  2. 在类型名上使用typeof操作符
System.Type

System.type 的属性有: 类型的名称, Assembly,基类等

using System;
public class Point {public int X, Y; }
class Test
{
  static void Main()
  {
    Point p = new Point();
    Console.WriteLine(p.GetTpye().Name); // Point
    Console.WriteLine(typeof(Point).Name); // Point
    Console.WriteLine(p.GetType() == typeof(Point); //true
    Console.WriteLine(p.X.GetType().Name); //Int32
    Console.WriteLine(p.Y.GetType().FullName); //System.Int32
  }
}

ToString()

int x = 1;
string s = x.ToString(); //s is "1"
public class Panda
{
  public string Name;
  public override string ToString() => Name;
}
...
Panda p = new Panda { Name = "Peter" };
Console.WriteLine(p) ; // Peter
上一篇 下一篇

猜你喜欢

热点阅读