Used to obtain the System.Type object for a type. A typeof expression takes the following form:
System.Type type = typeof(int);
To obtain the run-time type of an expression, you can use the .NET Framework method GetType, like this:
int i = 0; System.Type type = i.GetType();
The typeof operator can also be used on open generic types. Types with more then one type parameter must have the appropriate number of commas in the specification. The typeof operator cannot be overloaded.
// cs_operator_typeof.cs
using System;
using System.Reflection;
public class SampleClass
{
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:");
MethodInfo[] methodInfo = t.GetMethods();
foreach (MethodInfo mInfo in methodInfo)
Console.WriteLine(mInfo.ToString());
Console.WriteLine("Members:");
MemberInfo[] memberInfo = t.GetMembers();
foreach (MemberInfo mInfo in memberInfo)
Console.WriteLine(mInfo.ToString());
}
}
Output
Methods: Void SampleMethod() System.Type GetType() System.String ToString() Boolean Equals(System.Object) Int32 GetHashCode() Members: Void SampleMethod() System.Type GetType() System.String ToString() Boolean Equals(System.Object) Int32 GetHashCode() Void .ctor() Int32 sampleMember | |
This sample uses the GetType method to determine the type used to contain the result of a numeric calculation. This depends on the storage requirements of the resulting number.
// cs_operator_typeof2.cs
using System;
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 | |
本文介绍了C#中使用typeof操作符获取类型信息的方法,并展示了如何通过GetType方法取得运行时表达式的类型。此外,还提供了两个示例代码,分别演示了获取特定类型的信息及通过数学运算结果确定其类型。
530

被折叠的 条评论
为什么被折叠?



