ConstructorInfo
Конструктор получают из
GetConstructors.
Создание объекта -
Invoke.
Без отражения -
Activator.CreateInstance.
Синтаксис
ConstructorInfo ctor = type.GetConstructor(new Type[] { typeof(string) });
Пример
Давайте найти конструктор со строкой:
using System;
using System.Reflection;
class Gate
{
public Gate(string name)
{
Name = name;
}
public string Name { get; }
}
class Program
{
static void Main()
{
ConstructorInfo ctor = typeof(Gate).GetConstructor(new Type[] { typeof(string) });
bool res = ctor != null;
Console.WriteLine(res);
}
}
Результат выполнения кода:
True
Пример
Давайте создать объект через
Invoke:
using System;
using System.Reflection;
class Gate
{
public Gate(string name)
{
Name = name;
}
public string Name { get; }
}
class Program
{
static void Main()
{
ConstructorInfo ctor = typeof(Gate).GetConstructor(new Type[] { typeof(string) });
Gate gate = (Gate)ctor.Invoke(new object[] { "abcde" });
string res = gate.Name;
Console.WriteLine(res);
}
}
Результат выполнения кода:
"abcde"
Пример
Давайте посчитать открытые конструкторы:
using System;
using System.Reflection;
class Gate
{
public Gate()
{
}
public Gate(string name)
{
}
}
class Program
{
static void Main()
{
int res = typeof(Gate).GetConstructors().Length;
Console.WriteLine(res);
}
}
Результат выполнения кода:
2
Смотрите также
-
Invoke,
вызов конструктора -
Activator,
создание по типу -
GetConstructors,
список -
MethodInfo,
обычный метод