简体   繁体   English

有什么方法可以访问抽象类的派生类类型

[英]Is any way to get access to derived class type for abstract one

I want to make a data class that will contain some information and provide an event to work with that information. 我想制作一个数据类,其中将包含一些信息,并提供一个event以使用该信息。

public abstract class EventData<T> where T : EventData<T>
{
    Action<T> action_;
    public void Subscribe(Action<T> _actor) { action_ += _actor; }
    public void Unsubscribe(Action<T> _actor) { action_ -= _actor; }
    public void Dispatch(T _data) { if (action_ != null) action_(_data); }
}

public class ConcreteEventData : EventData<ConcreteEventData>
{
    int arg1;
    string arg2;
}

So, I forced to use that uncomfortable construction ConcreteEventData : EventData<ConcreteEventData> instead of simple and short ConcreteEventData : EventData even if I keep in mind that I would use the same type as I've described. 因此,即使我牢记要使用与上述相同的类型,我也不得不使用这种不舒服的结构ConcreteEventData : EventData<ConcreteEventData>而不是简单而又简短的ConcreteEventData : EventData Moreover, if someone will use that base class, he may write something like: 此外,如果某人将使用该基类,则他可能会编写如下内容:

public class AnotherConcreteEventData : EventData<ConcreteEventData>
{
    float arg1;
    bool arg2;
}

As you can see, it is not a good way to use that idea, is there another one to use it more elegance? 如您所见,这不是使用该想法的好方法,还有另一种方法可以使它更优雅吗?

Ok, solution was quite simple. 好的,解决方案很简单。 Instead of making a class for my "event", i could simple use EventArgs as data class with no event needed. 不用为我的“事件”创建类,我可以简单地将EventArgs用作不需要事件的数据类。 My goal was use it for EventBus, so instead of doing stuff like 我的目标是将其用于EventBus,而不是做类似的事情

public abstract class EventData<T> where T : EventData<T>
    {
        Action<T> action_;
        public void Subscribe(Action<T> _actor) { action_ += _actor; }
        public void Unsubscribe(Action<T> _actor) { action_ -= _actor; }
        public void Dispatch(T _data) { if (action_ != null) action_(_data); }
    }
    public class EventBus
    {
        static Dictionary<string, EventData> _dict;
    }

(moreovere, i cannot do that and i could be forced to find a solution for that problem too) I can simply use (此外,我不能那样做,我也可能被迫为该问题找到解决方案)我可以简单地使用

public class EventBus<T> where T : EventArgs
    {
        static Dictionary<string, Action<T>> list;

        public static void SubscribeOnEvent(string _sid, Action<T> _method)
        {
            // Do Stuff...
        }
    }

And use it in the way like 并以类似的方式使用

EventBus<MyData>.Subscibe("myID", (data) => { /*Do stuff...*/ });

And now i can use all the data, derived from EventArgs . 现在我可以使用从EventArgs派生的所有数据。 Thanks to @JeroenMostert for the idea. 感谢@JeroenMostert的想法。

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

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