型の System.Type オブジェクトを取得します。typeof 式は次の形式をとります。
System.Type type = typeof(int);
式の実行時の型を取得するには、次のように、.NET Framework のメソッド GetType を使用できます。
int i = 0;
System.Type type = i.GetType();
typeof 演算子は、オープン ジェネリック型に使用することもできます。複数の型パラメータが指定されている型では、仕様上、適切な数のコンマが使用されている必要があります。typeof 演算子はオーバーロードできません。
// 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());
}
}
出力
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
次の例では、GetType メソッドを使用して、数値計算の結果の格納に使用する型が決定されます。これは、結果として導かれた数値のストレージ要件によって異なります。
// 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()
);
}
}
出力
Area = 28.2743338823081
The type is System.Double
詳細については、「C# 言語仕様」の次のセクションを参照してください。
関連項目
C# のキーワード
is (C# リファレンス)
演算子キーワード (C# リファレンス)
概念
C# プログラミング ガイド
その他の技術情報
C# リファレンス