gpt4 book ai didi

c# - 从 Type 变量中获取实际类型

转载 作者:行者123 更新时间:2023-11-30 18:58:28 24 4
gpt4 key购买 nike

我正在尝试从 Type 变量中获取类型。例如:

Type t = typeof(String);
var result = SomeGenericMethod<t>();

第二行出错,因为t不是类型,它是一个变量。有什么办法让它成为一种类型吗?

最佳答案

要创建基于类型的泛型实例,您可以使用反射获取具有您要使用的类型的泛型实例,然后使用 Activator 创建该实例:

Type t = typeof (string); //the type within our generic

//the type of the generic, without type arguments
Type listType = typeof (List<>);

//the type of the generic with the type arguments added
Type generictype = listType.MakeGenericType(t);

//creates an instance of the generic with the type arguments.
var x = Activator.CreateInstance(generictype);

请注意,此处的x 将是一个对象。要对其调用函数,例如 .Sort(),您必须将其设为 dynamic

请注意此代码难以阅读、编写、维护、推理、理解或喜爱。如果您有任何需要使用这种结构的替代方案,请彻底研究

编辑:您还可以转换从Activator 接收到的对象,例如(IList)Activator.CreateInstance(genericType)。这将为您提供一些功能,而无需求助于动态。

关于c# - 从 Type 变量中获取实际类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38906204/

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