【问题标题】:I need to create an object of Class<T> but I dont know the T And my plan is to find T using generics but I dont know how我需要创建一个 Class<T> 的对象,但我不知道 T 我的计划是使用泛型找到 T 但我不知道如何
【发布时间】:2015-07-19 11:38:16
【问题描述】:

假设我们有一个像这样的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&lt;T&gt;,而不管它们的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)

这可能吗?

【问题讨论】:

  • 这个问题和你的另一个问题(stackoverflow.com/questions/31388962/…)非常相似。就像之前我严重怀疑您在这里采用的设计方法一样。您能否在更高的层次上描述您要解决的问题?更具体地说明我的担忧:为了正确封装和松散耦合,只有 NodeInput 应该知道如何填充其成员,而不是 Node 或任何其他类。
  • 最好把它放在Node&lt;T&gt; 构造函数中。这将消除反射的需要并强制执行类型安全。

标签: c# generics reflection generic-programming system.reflection


【解决方案1】:

如果我理解正确,您可以像这样获得节点泛型类型:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-07-27
    • 2021-09-01
    • 1970-01-01
    • 2010-12-20
    • 1970-01-01
    • 1970-01-01
    • 2021-09-19
    • 2023-02-03
    相关资源
    最近更新 更多