Csharp/CSharp Tutorial/Operator/typeof

Материал из .Net Framework эксперт
Перейти к: навигация, поиск

Assign returning value from "Typeof Operator" to "Type" variable

<source lang="csharp">using System; using System.Reflection; class MyClass {

  public int Field1;
  public int Field2;
  public void Method1() { }
  public int  Method2() { return 1; }

} class MainClass {

  static void Main()
  {
     Type t = typeof(MyClass);
     FieldInfo[] fi = t.GetFields();
     foreach (FieldInfo f in fi)
        Console.WriteLine("Field : {0}", f.Name);
  }

}</source>

We have a SomeClass object here

Demonstrate typeof

<source lang="csharp">using System; using System.IO;

class MainClass {

 public static void Main() { 
   Type t = typeof(StreamReader); 

   Console.WriteLine(t.FullName);     

   if(t.IsClass) 
        Console.WriteLine("Is a class."); 
   if(t.IsAbstract) 
        Console.WriteLine("Is abstract."); 
   else 
        Console.WriteLine("Is concrete."); 

 } 

}</source>

System.IO.StreamReader
Is a class.
Is concrete.

Obtain type information using the typeof operator

<source lang="csharp">using System; using System.Text; class MainClass {

   public static void Main()
   {
       Type t1 = typeof(StringBuilder);
   }

}</source>

typeof a Class name

<source lang="csharp">using System; using System.IO; class MainClass {

   public static void Main() 
   {
       Object someObject = new StringReader("This is a StringReader");
       if (typeof(StringReader) == someObject.GetType()) 
       {
           Console.WriteLine("typeof: someObject is a StringReader");
       }
   }

}</source>

typeof: someObject is a StringReader

Using typeof

You can use the "typeof" operator to obtain information about a type.

The typeof operator returns a System.Type object for a given type.

The typeof operator has this general form:


<source lang="csharp">typeof(type)</source>

type is the type being obtained.

The System.Type object returned encapsulates the information associated with type.

Using typeof operator in if statement

<source lang="csharp">using System; using System.Collections.Generic; using System.Text; class MainClass {

   static void Main(string[] args)
   {
       SomeClass someObject = new SomeClass();
       if (someObject.GetType() == typeof(SomeClass))
       {
           Console.WriteLine("We have a SomeClass object here");
       }
   }

} class SomeClass { }</source>

We have a SomeClass object here