C#中的typeof关键字

本文介绍了C#中使用typeof操作符获取类型信息的方法,并展示了如何通过GetType方法取得运行时表达式的类型。此外,还提供了两个示例代码,分别演示了获取特定类型的信息及通过数学运算结果确定其类型。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值