Reflecting and Activating Types

An instance of System.Type represents the metadata for a type.

Type Represents type declarations: class types, interface types, array types, value types, enumeration types, type parameters, generic type definitions, and open or closed constructed generic types.

You can get an instance of a System.Type by calling GetType on any object or with C#'s typeof operator:


using System;
using System.Reflection;

class Example
{
    static void Main()
    {
        Type t = typeof(String);

        MethodInfo substr = t.GetMethod("Substring", 
            new Type[] { typeof(int), typeof(int) });

        Object result = 
            substr.Invoke("Hello, World!", new Object[] { 7, 5 });
        Console.WriteLine("{0} returned \"{1}\".", substr, result);
    }
}

using System;
using System.Reflection;

class Main
{
    static void Main()
    {
        Type t1 = DateTime.Now.GetType(); // Type obtained at runtime
        Type t2 = typeof(DateTime); // Type obtained at compile time
    }
}
java2s.com  | Contact Us | Privacy Policy
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.