C#--取得類型的方法--object.GetType() v.s. typeof(object) ...

 C#--取得類型的方法--object.GetType() v.s. typeof(object)  ...

在這篇文章,我要介紹有關取得類型的關鍵字。

 這些事我上網查到的我盡量用簡單敘述來詳細地描述複雜的事。

目錄:

 C#--取得類型的方法

 C#--比較相同類型的方法

 C#--判斷為某種類型的方法

 C#--typeof(object)

 C#--object.GetType()

 C#--is keyword

 C#--not keyword

 C#--in keyword

 NOTE


 C#--取得類型的方法

way1:typeof(object)
way2:object.GetType()

 C#--比較相同類型的方法

way1:typeof(object1)==typeof(object2)
way2:typeof(object1)==object2.GetType()

 C#--判斷為某種類型的方法

way1:typeof(object1)==typeof(int)
way2:typeof(int)==object1.GetType()
way3:int x=object1 as int; if(x!=null)


 C#--typeof(object)

獲取在編譯時指定的類型名,object 必須為static class,不能為nonstatic class(被具體化的類別)。



C#--object.GetType()

獲得一個實例在運行時的類型,不一定為nonstatic class。

C#--as keyword

B=A as int 
A會試著被轉成 int ,當A無法被轉成int,B會是null。

 C#--is keyword

object1 is object2
判斷object1 是object2 的子類別,判斷object1 是object2 的孩子。

 C#--not keyword

"not" is a keyword that is usually used with "is" which takes opposition.

//I remember that "not" is supported in C# 9.0 version.

e.g.:
if(object1 is not object2)
{
//op1
}
//when object1 is a class which is object2, object1 is object2 may return true.
//and object1 is object2 may return false;

 C#--in keyword 

It can be used in iterator or foreach loop. 
It is not related to the point of this article.
It is  appendix.
e.g.:
int []NumArray=new int[]{1,2,3,4,5};
foreach(var x in NumArray)
{
Console.WriteLine(x);
}
/*
output:
1
2
3
4
5
*/

/*
At first, x will be the first element of NumArray. x=1.
At second, x will be the second element of NumArray. x=2.
At third, x will be the third element of NumArray. x=3.
...
At last, x will be the last element of NumArray. x=5.
*/

 NOTE

(1)typeof(object1) can not used in nonstatic class.
e.g.
class BaseClass
{

}
public static void Main()
{
BaseClass b=new BaseClass();
int x=5;
if(typeof())x++;
}

(2)typeof(object1) is determined at compile time.

(3)object1.GetType() is determined when the object is instantiated at running time.

(4)according to (2) and (3), 
typeof(object1)==typeof(object2)
typeof(object1)==object2.GetType()
object2.GetType()==object2.GetType()
are not complete same.


(5)
B=A as int; 
B=(int)A;
is not same.
When A can not be converted into a variable which is int type.
B=A as int; //B will be null
B=(int)A; // may thorw execeptions at running time in Visual Studio.


source:

Comments

Popular posts from this blog

String Interpolation(字串內插)

Format a string -- String.Format()