网摘 |  收藏 | 

typeof(C# 参考)

http://technet.microsoft.com/zh-cn/windows/58918ffs.aspx

用于获取类型的 System.Type 对象。 typeof 表达式采用以下形式:

System.Type type = typeof(int);
备注

若要获取表达式的运行时类型,可以使用 .NET Framework 方法 GetType,如以下示例中所示:

int i = 0;
System.Type type = i.GetType();

不能重载 typeof 运算符。

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

string s = method.ReturnType.GetInterface
    (typeof(System.Collections.Generic.IEnumerable<>).FullName);
示例
  1. public class ExampleClass
  2. {
  3.    public int sampleMember;
  4.    public void SampleMethod() {}
  5.  
  6.    static void Main()
  7.    {
  8.       Type t = typeof(ExampleClass);
  9.       // Alternatively, you could use
  10.       // ExampleClass obj = new ExampleClass();
  11.       // Type t = obj.GetType();
  12.  
  13.       Console.WriteLine("Methods:");
  14.       System.Reflection.MethodInfo[] methodInfo = t.GetMethods();
  15.  
  16.       foreach (System.Reflection.MethodInfo mInfo in methodInfo)
  17.          Console.WriteLine(mInfo.ToString());
  18.  
  19.       Console.WriteLine("Members:");
  20.       System.Reflection.MemberInfo[] memberInfo = t.GetMembers();
  21.  
  22.       foreach (System.Reflection.MemberInfo mInfo in memberInfo)
  23.          Console.WriteLine(mInfo.ToString());
  24.    }
  25. }
  26. /*
  27.  Output:
  28.     Methods:
  29.     Void SampleMethod()
  30.     System.String ToString()
  31.     Boolean Equals(System.Object)
  32.     Int32 GetHashCode()
  33.     System.Type GetType()
  34.     Members:
  35.     Void SampleMethod()
  36.     System.String ToString()
  37.     Boolean Equals(System.Object)
  38.     Int32 GetHashCode()
  39.     System.Type GetType()
  40.     Void .ctor()
  41.     Int32 sampleMember
  42. */
  43.  

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

  1. class GetTypeTest
  2. {
  3.     static void Main()
  4.     {
  5.         int radius = 3;
  6.         Console.WriteLine("Area = {0}", radius * radius * Math.PI);
  7.         Console.WriteLine("The type is {0}",
  8.                           (radius * radius * Math.PI).GetType()
  9.         );
  10.     }
  11. }
  12. /*
  13. Output:
  14. Area = 28.2743338823081
  15. The type is System.Double
  16. */
  17.  
C# 语言规范

 

有关更多信息,请参见 C# 语言规范。C# 语言规范是 C# 语法和用法的权威资料。

posted @ 2012-11-12 10:47  xulonghua219  阅读(207)  评论(0编辑  收藏  举报