- 相關(guān)推薦
運(yùn)算符關(guān)鍵字typeof的使用
引導(dǎo)語:C語言是一種計(jì)算機(jī)程序設(shè)計(jì)語言,它既具有 高級(jí)語言的特點(diǎn),又具有 匯編語言的特點(diǎn)。以下是小編整理的運(yùn)算符關(guān)鍵字typeof的使用,歡迎參考閱讀!
用于獲取類型的 System.Type 對(duì)象。typeof 表達(dá)式采用以下形式:
System.Type type = typeof(int);
備注
若要獲取表達(dá)式的運(yùn)行時(shí)類型,可以使用 .NET Framework 方法 GetType,如以下示例中所示:
int i = 0;
System.Type type = i.GetType();
不能重載 typeof 運(yùn)算符。
typeof 運(yùn)算符也能用于公開的泛型類型。具有不止一個(gè)類型參數(shù)的類型的規(guī)范中必須有適當(dāng)數(shù)量的逗號(hào)。下面的示例演示如何確定方法的返回類型是否是泛型 IEnumerable<(Of <(t>)>)。假定此方法是 MethodInfo 類型的實(shí)例:
string s = method.ReturnType.GetInterface
(typeof(System.Collections.Generic.IEnumerable<>).FullName
示例
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 = obj.GetType();
Console.WriteLine("Methods:");
System.Reflection.MethodInfo[] methodInfo = t.GetMethods();
foreach (System.Reflection.MethodInfo mInfo in methodInfo)
Console.WriteLine(mInfo.ToString());
Console.WriteLine("Members:");
System.Reflection.MemberInfo[] memberInfo = t.GetMembers();
foreach (System.Reflection.MemberInfo mInfo in memberInfo)
Console.WriteLine(mInfo.ToString());
}
}
/*
Output:
Methods:
System.Type GetType()
System.String ToString()
Boolean Equals(System.Object)
Int32 GetHashCode()
Members:
System.Type GetType()
System.String ToString()
Boolean Equals(System.Object)
Int32 GetHashCode()
Void .ctor()
Void .ctor(Int32, System.String)
System.String name
Int32 id
*/
此示例使用 GetType 方法確定用來包含數(shù)值計(jì)算的結(jié)果的類型。這取決于結(jié)果數(shù)字的存儲(chǔ)要求。
C#
class GetTypeTest
{
static void Main()
{
int radius = 3;
Console.WriteLine("Area = {0}", radius * radius * Math.PI);
Console.WriteLine("The type is {0}",
(radius * radius * Math.PI).GetType()
);
}
}
/*
Output:
Area = 28.2743338823081
The type is System.Double
*/
【運(yùn)算符關(guān)鍵字typeof的使用】相關(guān)文章:
java語言運(yùn)算符的使用10-02
Java中運(yùn)算符的使用10-17
C語言關(guān)鍵字const的使用09-02
C語言的關(guān)鍵字enum的使用09-24