如何访问一个方法的传递作为参数来一个泛型函数在C#中的对象上 [英] How to access a method on an object that's passed in as a parameter to a Generic Function in C#

查看:774
本文介绍了如何访问一个方法的传递作为参数来一个泛型函数在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 (temp != null)
            {
                temp.Invoke(this, evt);
            }
        }



我希望能够在调用Invoke方法温度,这是类型T的有没有办法做到这一点?

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

感谢您。

推荐答案

您可能会更多的东西等之后:

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);
    }

这篇关于如何访问一个方法的传递作为参数来一个泛型函数在C#中的对象上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆