Csharp/CSharp Tutorial/Operator/typeof

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

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

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);
   }
}
We have a SomeClass object here

Demonstrate typeof

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."); 
 
  } 
}
System.IO.StreamReader
Is a class.
Is concrete.

Obtain type information using the typeof operator

using System;
using System.Text;
class MainClass
{
    public static void Main()
    {
        Type t1 = typeof(StringBuilder);
    }
}

typeof a Class name

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");
        }
    }
}
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:


typeof(type)

type is the type being obtained.

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

Using typeof operator in if statement

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
{
}
We have a SomeClass object here