开发者

How to access a method on an object that's passed in as a parameter to a Generic Function in C#

I have a generic method that has some parameter of a generic Type. What I want to do, is be able to access the method on this generic type parameter inside my function.

    public void dispatchEvent<T>(T handler, EventArgs evt)
        {
            T temp = handler; // make a copy to be more thread-safe
            if (t开发者_Go百科emp != null)
            {
                temp.Invoke(this, evt);
            }
        }

I want to be able to call the Invoke method on temp, which is of type T. Is there a way to do this?

Thank You.


Use a constraint for the generic:

public void dispatchEvent<T>(T handler, EventArgs evt) where T : yourtype


You might be after something more like:

        public void dispatchEvent<T>(EventHandler<T> handler, T evt) 
            where T: EventArgs
        {
            if (handler != null)
                handler(this, evt);
        }

Just for fun, here it is as an extension method:

    public static void Raise<T>(this EventHandler<T> handler, Object sender, T args)
        where T : EventArgs
    {
        if (handler != null)
            handler(sender, args);
    }


How about this :

    public void dispatchEvent<T>(T handler, EventArgs evt)
    {
        T temp = handler; // make a copy to be more thread-safe
        if (temp != null && temp is Delegate)
        {
            (temp as Delegate).Method.Invoke((temp as Delegate).Target, new Object[] { this, evt });
        }
    }
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜