我需要创建一个Class<;T>;但是我不知道T,我的计划是用泛型找到T,但我不知道怎么做

本文关键字:我不知道 我的 计划 泛型 gt 创建 lt Class 一个 | 更新日期: 2023-09-27 18:03:21

假设我们有一个NodeInput类,如下所示:

public class NodeInput
{
}
public sealed class NodeInput<T> : NodeInput
{
}

我们有一个Node类,如下所示:

public abstract class Node
{
    public Node()
    {
        var fieldInfos = GetType().GetRuntimeFields();
        // loop through all NodeInputs using their concrete base type
        foreach (var item in fieldInfos)
        {
            Type t = item.FieldType;
            if (t.BaseType == typeof(NodeInput))
            {
                // Here I want to initialize each NodeInput field according to
                // the T but I don't know what the T is here. 
            }
        }
    }
}

我已经创建了具体的父类NodeInput,这样我就可以对所有NodeInput<T>进行计数,而不管它们的T参数类型如何。但我也需要T来创建适当的对象并分配给循环中的每个字段。例如,以下代码中的PointNode应该在创建对象时使用default(T)初始化所有NodeInput字段:

 public class PointNode : Node
{
    public NodeInput<double> x;
    public NodeInput<int> y;
    public NodeInput<float> z;
}
PointNode node = new PointNode (); 
// Now x,y and z should be 0 = default(double),default(int),default(float)

这可能吗?

我需要创建一个Class<;T>;但是我不知道T,我的计划是用泛型找到T,但我不知道怎么做

如果我理解得对,你可以得到这样的节点泛型类型:

var genericType = item.FieldType.GenericTypeArguments[0];