Метод Invoke
Первый аргумент у конструктора не нужен - передают только массив параметров. Результат - новый объект.
Синтаксис
object item = ctor.Invoke(new object[] { "abcde" });
Пример
Давайте создать Gate
со строкой abcde:
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 string Name;
public Gate(string name)
{
Name = name;
}
}
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 int Count;
public Gate()
{
Count = 12345;
}
}
class Program
{
static void Main()
{
ConstructorInfo ctor = typeof(Gate).GetConstructor(Type.EmptyTypes);
Gate gate = (Gate)ctor.Invoke(null);
int res = gate.Count;
Console.WriteLine(res);
}
}
Результат выполнения кода:
12345
Смотрите также
-
CreateInstance,
создание без ctor -
ConstructorInfo,
обзор -
MethodInfo.Invoke,
вызов метода -
GetConstructors,
поиск конструктора