gpt4 book ai didi

c# - 如何在运行时填写构造函数参数?

转载 作者:行者123 更新时间:2023-11-30 20:59:54 24 4
gpt4 key购买 nike

我想创建一个类型的实例,但直到运行时我才知道类型。

如何获取构造函数所需的参数以在 WPF 窗口中将它们显示给用户?

Visual Studio 中有类似Properties Window 的东西可以使用吗?

最佳答案

查看可以从反射类型中获取的 ParameterInfo 对象:

Type type = typeof(T); 
ConstructorInfo[] constructors = type.GetConstructors();

// take one, for example the first:
var ctor = constructors.FirstOrDefault();

if (ctor != null)
{
ParameterInfo[] params = ctor.GetParameters();

foreach(var param in params)
{
Console.WriteLine(string.Format("Name {0}, Type {1}",
param.Name,
param.ParameterType.Name));
}
}

关于c# - 如何在运行时填写构造函数参数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15265984/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com