从属性中设置泛型 () 的类型

本文关键字:类型 设置 泛型 从属性 | 更新日期: 2023-09-27 18:37:09

我想实现如下

// Property
public static T Type
{ get; set; }
private void Form1_Load(...)
{
    List<Type> abc = new ...
    // code.....

如上所述,当我加载Form1时,必须定义类型为 = Type (the property)List。我怎样才能做到这一点?

从属性中设置泛型 (<T>) 的类型

Type

属性的名称,T是类型名称。

List<T> abc = new List<T>();

当然,我假设您已将封闭类参数化为class CustomForm<T>

不确定为什么要使用属性进行设置,或者是否可能 - 您希望能够在实例化或其他东西之后更改类型吗?

如果你没有一些非常特殊的需求,也许你可以用这个?

private void Form1_Load<T>(...)  // Pass the type in here
{
    List<T> abc = new List<T>(); 
}

用法:

this.Form1_Load<targetType>(...); 

或者,在实例化包含 Form1_Load() 的类时传入类型:

class Container<T>
{
    private void Form1_Load(...)
    {
        List<T> abc = new List<T>(); 
    }
}

用法:

var instance = new Container<targetType>(); 

你可以创建一个这样的类生成器:

public class GenericBuilder
{
    public Type ParamType { get; set; }
    public object CreateList() {
        var listType = typeof(List<>);
        ArrayList alist = new ArrayList();
        alist.Add( this.ParamType );
        var targetType = listType.MakeGenericType( (Type[])alist.ToArray(typeof(Type)) );
        return Activator.CreateInstance( targetType );
    }
}

然后你可以使用它:

var builder = new GenericBuilder();
builder.ParamType = typeof( int );
var result = builder.CreateList();