我目前正在构建一个节点编辑器(as in Blender),并且无法从泛型类型获取委托给属性访问器。到目前为止,here这个问题给我带来了最接近的,但我遇到了麻烦,我认为它与通用对象的类型具体相关。如何从泛型类型获取委托给属性访问器?
作为参考,“节点”与对象同义,“端口”与属性同义。
这是违规的代码,它是类Node
的一部分。 NodePort
类是可以在属性上设置的属性,以提供属性的详细信息(例如人类可读名称和数据流向)。
public void SetTarget<T>(T Target)
{
//TODO: Finish clearing old IOs (if any)
Inputs.Clear();
Outputs.Clear();
//Keep track of the current target of this node.
ThisTarget = Target;
PropertyInfo[] pinfo = Target.GetType().GetProperties();
foreach (PropertyInfo property in pinfo)
{
Attribute[] attrs = Attribute.GetCustomAttributes(property);
foreach (Attribute attribute in attrs)
{
// If the property has a NodePort attribute, it's specifically requesting to be available as a port on the node.
if (attribute is NodePort)
{
NodePort PortDetails = (NodePort)attribute;
if (PortDetails.Direction == NodePort.NodePortDirection.PORT_INPUT)
{
// This line throws an ArgumentException, and the only message is "Error binding to target method."
NodeInput<T>.SetValue Setter = (NodeInput<T>.SetValue)Delegate.CreateDelegate(typeof(NodeInput<T>.SetValue), (T)Target, property.GetSetMethod());
AddInput(Setter, PortDetails.CommonName);
}
else if (PortDetails.Direction == NodePort.NodePortDirection.PORT_OUTPUT)
{
// Same exception here.
NodeOutput<T>.GetValue Getter = (NodeOutput<T>.GetValue)Delegate.CreateDelegate(typeof(NodeOutput<T>.GetValue), (T)Target, property.GetGetMethod());
AddOutput(Getter, PortDetails.CommonName);
}
}
}
}
}
NodeOutput<T>.GetValue
和NodeInput<T>.SetValue
被定义为这样:
public delegate T GetValue();
public delegate void SetValue(T value);
...分别NodeOutput
和NodeInput
。
有没有人有任何经验与财产访问者创建代表?任何想法如何可能会有所不同,当问题的类型是通用的?
任何类型的属性都可以用* NodePort *来装饰吗? – Elisha 2009-10-17 08:36:16
是的。 'NodePort'可以应用于任何属性。 – 2009-10-17 08:56:55