using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Exercisc : MonoBehaviour
{
public class A
{
}
public class B : A
{
}
private void Start()
{
A a = new A();
B b = new B();
A ab = new B();
Debug.Log("a is A ="+ (a is A));
Debug.Log("b is A =" + (b is A));
Debug.Log("ab is A =" + (ab is A));
Debug.Log("a is B =" + (a is B));
Debug.Log("b is B =" + (b is B));
Debug.Log("ab is B =" + (ab is B));
//
a is A =True
b is A =True
ab is A =True
a is B =False
b is B =True
ab is B =True
}
}
E is T v
E is T v 運算式會傳回 true,E 的結果會指派至變數v(可以使用在if子句)
as運算子
功用:as運算子將運算式的結果明確地轉換成給定參考或可為 Null 的實值型別。
如果無法轉換,則 as 運算子會傳回 null。
與強制轉換表示式不同as, 運算子從不引發異常。
限制
1.as 運算子只考慮參考、可為 Null、Boxing 和 Unboxing 轉換
2.您無法使用as 運算子來執行使用者定義轉換。 不過可以使用強制轉換表示式解決。
E as T//和這個程式碼是一樣的E is T ? (T)(E) : (T)null
其中 E 是會傳回值的運算式,而 T 是型別名稱或型別參數
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
public class Exercisc : MonoBehaviour
{
private void Start()
{
int[] num = new[] { 15, 25, 35 };
IList<int> list_num = num as IList<int>;
if (list_num != null)
{
Debug.Log(list_num[0]+"和"+list_num[1]+"和"+list_num[2]);
}
//15和25和35
}
}
轉換運算式
功用:格式為 (T)E 的轉換運算式會執行明確轉換,將運算式 E 的結果轉換成型別 T。
如果沒有從型別E 轉換成型別 T 的明確轉換存在,就會發生編譯時期錯誤。
在執行階段,明確轉換可能不會成功,且轉換運算式可能會擲回例外狀況。
double a = 8787.7777;int a = (int)b;
Debug.Log(a);//8787
typeof運算子
功用:取得型別的 System.Type 執行個體
1.typeof 運算子的引數必須是型別名稱或型別參數如int,string 等類型及自定義類型,不能是實例。
2.您還可以使用運算子typeof與未綁定的泛型類型
3.運算式不能作為 typeof 運算子的引數
4.Gettype返回的是實例的type(類型),而typeof返回的是Class(類)的類型。
using System.Collections;
using System.Collections.Generic;
using UnityEngine;
using System;
public class Exercisc : MonoBehaviour
{
public delegate Func<int,string> Del_A();
public class A
{
}
public class B : A
{
}
private void Start()
{
A a = new A();
B b = new B();
A ab = new B();
Debug.Log("a is A =" + (a is A));
Debug.Log("b is A =" + (b is A));
Debug.Log("ab is A =" + (ab is A));
Debug.Log("a is B =" + (a is B));
Debug.Log("b is B =" + (b is B));
Debug.Log("ab is B =" + (ab is B));
Debug.Log("~~~~~~~~~~~~~~~~~~~~~~~~");
Debug.Log("typeof(A) =" + typeof(A));
Debug.Log("typeof(B) =" + typeof(B));
Debug.Log("typeof(string) =" + typeof(string));
Debug.Log("typeof(string) =" + typeof(Del_A));
Debug.Log("~~~~~~~~~~~~~~~~~~~~~~~~");
Debug.Log(a.GetType() ==typeof(A));
Debug.Log(b.GetType() == typeof(A));
Debug.Log(ab.GetType() == typeof(A));
Debug.Log(a.GetType() == typeof(B));
Debug.Log(b.GetType() == typeof(B));
Debug.Log(ab.GetType() == typeof(B));
//
a is A =True
b is A =True
ab is A =True
a is B =False
b is B =True
ab is B =True
~~~~~~~~~~~~~~~~~~~~~~~~
typeof(A) =Exercisc+A
typeof(B) =Exercisc+B
typeof(string) =System.String
typeof(string) =Exercisc+Del_A
~~~~~~~~~~~~~~~~~~~~~~~~
True(不能和string一起使用Debug.Log("No"ab.GetType() ==typeof(B));不行)
False
False
False
True
True
}
}