Csharp/C Sharp/Reflection/ConstructorInfo — различия между версиями

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

Версия 15:31, 26 мая 2010

Call GetConstructor to get the constructor

 
using System;
using System.Text;
using System.Reflection;
class MainClass
{
    public static StringBuilder CreateStringBuilder()
    {
        Type type = typeof(StringBuilder);
        Type[] argTypes = new Type[] { typeof(System.String), typeof(System.Int32) };
        ConstructorInfo cInfo = type.GetConstructor(argTypes);
        object[] argVals = new object[] { "Some string", 30 };
        StringBuilder sb = (StringBuilder)cInfo.Invoke(argVals);
        return sb;
    }
}


Get parameter information by using ConstructorInfo and ParameterInfo

 
using System;
using System.Collections;
using System.Reflection;
public class MainClass{
    public static void Main() {
        Assembly LoadedAsm = Assembly.LoadFrom("yourName");
        Console.WriteLine(LoadedAsm.FullName);
        Type[] LoadedTypes = LoadedAsm.GetTypes();
        if (LoadedTypes.Length == 0) {
            Console.WriteLine("\tNo Types!");
        } else {
            Console.WriteLine("\tFound Types:");
            foreach (Type t in LoadedTypes) {
                if (t.IsPublic && !t.IsEnum && !t.IsValueType) {
                    Console.WriteLine("Type: {0}", t.FullName);
                    PrintConstructorInfo(t);
                }
            }
        }
    }
    private static  void PrintConstructorInfo(Type t) {
        ConstructorInfo[] ctors = t.GetConstructors();
        foreach (ConstructorInfo c in ctors) {
            ParameterInfo[] pList = c.GetParameters();
            if (pList.Length == 0) {
                if (c.IsStatic)
                    Console.WriteLine("\tFound static Constructor.");
                else
                    Console.WriteLine("\tFound default consructor.");
            } else {
                Console.WriteLine("\tConstructor:");
                foreach (ParameterInfo p in pList) {
                    Console.WriteLine("\t\t{0} {1}", p.ParameterType.FullName,p.Name);
                }
            }
        }
    }
}


Invoke in Constructor through ConstructorInfo

using System;
using System.Text;
using System.Reflection;
class MainClass {
    public static void Main() {
        Type type = typeof(StringBuilder);
        Type[] argTypes = new Type[] { typeof(System.String), typeof(System.Int32) };
        ConstructorInfo cInfo = type.GetConstructor(argTypes);
        object[] argVals = new object[] { "Some string", 30 };
        StringBuilder sb = (StringBuilder)cInfo.Invoke(argVals);
        Console.WriteLine(sb.ToString());
        
    }
}