運算符關鍵字typeof的使用

來源:文萃谷 1.35W

引導語:C語言是一種計算機程序設計語言,它既具有 高級語言的特點,又具有 彙編語言的特點。以下是小編整理的運算符關鍵字typeof的'使用,歡迎參考閲讀!

運算符關鍵字typeof的使用

用於獲取類型的 對象。typeof 表達式採用以下形式:

type = typeof(int);

  備註

若要獲取表達式的運行時類型,可以使用 Framework 方法 GetType,如以下示例中所示:

int i = 0;

type = ype();

不能重載 typeof 運算符。

typeof 運算符也能用於公開的泛型類型。具有不止一個類型參數的類型的規範中必須有適當數量的逗號。下面的示例演示如何確定方法的返回類型是否是泛型 IEnumerable<(Of <(t>)>)。假定此方法是 MethodInfo 類型的實例:

string s = nterface

(typeof(merable<>)Name

  示例

C#

public class SampleClass2

{

public int sampleMember;

public void SampleMethod() {}

static void Main()

{

Type t = typeof(SampleClass);

// Alternatively, you could use

// SampleClass obj = new SampleClass();

// Type t = ype();

eLine("Methods:");

odInfo[] methodInfo = ethods();

foreach (odInfo mInfo in methodInfo)

eLine(ring());

eLine("Members:");

erInfo[] memberInfo = embers();

foreach (erInfo mInfo in memberInfo)

eLine(ring());

}

}

/*

Output:

Methods:

GetType()

ng ToString()

Boolean Equals(ct)

Int32 GetHashCode()

Members:

GetType()

ng ToString()

Boolean Equals(ct)

Int32 GetHashCode()

Void ()

Void (Int32, ng)

ng name

Int32 id

*/

此示例使用 GetType 方法確定用來包含數值計算的結果的類型。這取決於結果數字的存儲要求。

C#

class GetTypeTest

{

static void Main()

{

int radius = 3;

eLine("Area = {0}", radius * radius * );

eLine("The type is {0}",

(radius * radius * )ype()

);

}

}

/*

Output:

Area = 28.2743338823081

The type is le

*/

熱門標籤