C#中Typeof是干什么的?

如题所述

MSDN上typeof的说明:“用于获取类型的 System.Type 对象。”

typeof是操作符(一些书叫运算符),这点很重要。在C#中所有的操作符最后都变为函数了。这也就不奇怪为什么一个看似函数的东西却被称为操作符的原因了。

注意返回的是Type对象,内含有许多信息。如类型的信息。方法有哪些,属性有哪些,字段有哪些。如果用其它的技术,如反射、序列化什么的,配合使用的话会更方便。


扩展资料

typeof(x)中的x,必须是具体的类名、类型名称等,不可以是变量名称。

GetType()方法继承于Object(C#中所有类的基类都是object类。基类是相对于派生类而言的,比方说:如果B类继承自A类,则A就是B的基类。),所以C#中任何对象都具有GetType()方法,它的作用和typeof()相同,返回Type类型的当前对象的类型。

举例说明:

有这样一个变量i: Int32 i = new Int32();

i.GetType()返回值是Int32的类型,但是无法使用typeof(i),因为i是一个变量。如果要使用typeof(),则只能:typeof(Int32),返回的同样是Int32的类型。

Typeof()是运算符,用于获取类型的 System.Type 对象。而GetType是方法,获取当前实例的类型;Typeof()的参数只能是int,string,String,自定义类型,且不能是实例;

温馨提示:答案为网友推荐,仅供参考
第1个回答  推荐于2017-11-28
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的类型。本回答被提问者采纳
第2个回答  2012-12-07
在js里用到数组,typeof(x)中的x,必须是具体的类名、类型名称等,不可以是变量名称。
第3个回答  2011-10-21
Typeof 翻译为各种类型
第4个回答  2011-11-03
用于获取类型的 System.Type 对象。 typeof 表达式采用以下形式:

System.Type type = typeof(int);

不能重载 typeof 运算符。

typeof 运算符也能用于公开的泛型类型。 具有不止一个类型参数的类型的规范中必须有适当数量的逗号。 下面的示例演示如何确定方法的返回类型是否是泛型 IEnumerable(Of T)。 假定此方法是 MethodInfo 类型的实例:

string s = method.ReturnType.GetInterface
(typeof(System.Collections.Generic.IEnumerable<>).FullName);

public class ExampleClass
{
public int sampleMember;
public void SampleMethod() {}

static void Main()
{
Type t = typeof(ExampleClass);
// Alternatively, you could use
// ExampleClass obj = new ExampleClass();
// 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:
Void SampleMethod()
System.String ToString()
Boolean Equals(System.Object)
Int32 GetHashCode()
System.Type GetType()
Members:
Void SampleMethod()
System.String ToString()
Boolean Equals(System.Object)
Int32 GetHashCode()
System.Type GetType()
Void .ctor()
Int32 sampleMember
*/

此示例使用 GetType 方法确定用来包含数值计算的结果的类型。 这取决于结果数字的存储要求。

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
*/