|
C# typeof() 和 GetType()区是什么?
1、typeof(x)中的x,必须是具体的类名、类型名称等,不可以是变量名称。
2、GetType()方法继承自Object,所以C#中任何对象都具有GetType()方法,它的作用和typeof()相同,返回Type类型的当前对象的类型。
比如有这样一个变量i:
Int32 i = new Int32();
i.GetType()返回值是Int32的类型,但是无法使用typeof(i),因为i是一个变量,如果要使用typeof(),则只能:typeof(Int32),返回的同样是Int32的类型。
- 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());
- }
- }
复制代码 输出
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
- 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()
- );
- }
- }
复制代码 输出
Area = 28.2743338823081
The type is System.Double
|
上一篇: 新路由3(newifi)原厂固件插件大全下一篇: c# Marshal.PtrToStructure
|