简体   繁体   English

从非泛型基类调用泛型方法/委托

[英]Invoking generic method/delegate from a non-generic base class

I have the feeling I'm not looking at this issue from the right angle here, and I'm just not thinking of other solution. 我觉得我不是从正确的角度看待这个问题,而我只是没有考虑其他解决方案。

Assuming this generic class; 假设这个泛型类;

public abstract class Port<T>
{
    public delegate T PullDelegate();

    private PullDelegate pull;

    public Port(PullDelegate pull)
    {
        this.pull = pull;
    }

    public T Pull()
    {
        return pull();
    }
}

It is used to define "ports" in a graph-node editor. 它用于在图形节点编辑器中定义“端口”。 A port can transfer a object/value from one node to another, but they also need to be "type-safe", which means I cannot plug any port to another of the wrong type (at least not without some conversion). 端口可以​​将对象/值从一个节点传输到另一个节点,但它们也需要是“类型安全的”,这意味着我无法将任何端口插入另一个错误类型的端口(至少没有一些转换)。

The node "owns" a port and give it a delegate towards one of its method so when another node "pull" on a value, the port simply invokes it and returns the proper value. 节点“拥有”一个端口并为其一个方法赋予它一个委托,因此当另一个节点“拉”一个值时,该端口只是调用它并返回正确的值。

My issue starts when I'm trying to call Pull() from a non-generic collection. 当我试图从非泛型集合中调用Pull()时,我的问题开始了。 Obviously, I could make a non-generic base method, but then Pull could not return T , it would need to return object . 显然,我可以创建一个非泛型的基本方法,但是然后Pull不能返回T ,它需要返回object

Also, each nodes have collection accessors for their ports so the other items can get them. 此外,每个节点都有其端口的集合访问器,因此其他项目可以获取它们。 That collect has to be non-generic because a node can have many ports of many type. 该收集必须是非泛型的,因为一个节点可以有许多类型的许多端口。

    public abstract Port[] Inputs { get; }
    public abstract Port[] Outputs { get; }
    public abstract Port[] Entries { get; }
    public abstract Port[] Exits { get; }

The moment the non-generic type get into play, everything generic become inaccessible. 非泛型类型发挥作用的那一刻,通用的一切都变得无法访问。 If only Port<>[] would be a thing. 如果只有Port<>[]会成为一件事。

I'm feeling like I'm missing something... 我觉得我错过了什么......

Make Port<T> implement the non-generic interface IPort using explicit implementations. 使Port<T>使用显式实现实现非通用接口IPort In that way it's hidden from the API but still allow you to invoke methods in the generic classes. 以这种方式,它隐藏在API之外,但仍然允许您调用泛型类中的方法。

public interface IPort
{
    object SomeAction(object data);
}

public class Port<T> : IPort
{
    //[.. all other methods ..]


    object IPort.SomeAction(object data)
    {
        var typedData = (T)data;
        //invoke our typed version.
        return SomeAction(data);
    }

    public T SomeAction(T data)
    {
         // ...
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM