【发布时间】: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<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)
这可能吗?
【问题讨论】:
-
这个问题和你的另一个问题(stackoverflow.com/questions/31388962/…)非常相似。就像之前我严重怀疑您在这里采用的设计方法一样。您能否在更高的层次上描述您要解决的问题?更具体地说明我的担忧:为了正确封装和松散耦合,只有 NodeInput 应该知道如何填充其成员,而不是 Node 或任何其他类。
-
最好把它放在
Node<T>构造函数中。这将消除反射的需要并强制执行类型安全。
标签: c# generics reflection generic-programming system.reflection