Создаем портфолио за 1 месяц
К концу месяца: 4 классных проекта в вашем портфолио! Стоимость: 100$. Подробности...
1459 of 1492 menu
◀ ▶

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

Смотрите также

← →
↑
Мы используем cookie для работы сайта, аналитики и персонализации. Обработка данных происходит согласно Политике конфиденциальности.
принять все настроить отклонить