使用运行时类型执行的泛型方法 [英] Generic Method Executed with a runtime type

查看:29
本文介绍了使用运行时类型执行的泛型方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下代码:

 public class ClassExample
{

    void DoSomthing<T>(string name, T value)
    {
        SendToDatabase(name, value);
    }

    public class ParameterType
    {
        public readonly string Name;
        public readonly Type DisplayType;
        public readonly string Value;

        public ParameterType(string name, Type type, string value)
        {
            if (string.IsNullOrEmpty(name))
                throw new ArgumentNullException("name");
            if (type == null)
                throw new ArgumentNullException("type");

            this.Name = name;
            this.DisplayType = type;
            this.Value = value;
        }
    }

    public void GetTypes()
    {
        List<ParameterType> l = report.GetParameterTypes();

        foreach (ParameterType p in l)
        {
            DoSomthing<p.DisplayType>(p.Name, (p.DisplayType)p.Value);
        }

    }
}

现在,我知道我不能执行 DoSomething()还有其他方法可以使用这个功能吗?

Now, I know I cannot perform DoSomething() is there any other way to use this function?

推荐答案

你可以,但是涉及到反射,但是你可以做到.

You can, but it involves reflection, but you can do it.

typeof(ClassExample)
    .GetMethod("DoSomething")
    .MakeGenericMethod(p.DisplayType)
    .Invoke(this, new object[] { p.Name, p.Value });

这将查看包含类的顶部,获取方法信息,创建具有适当类型的泛型方法,然后您可以对其调用 Invoke.

This will look at the top of the containing class, get the method info, create a generic method with the appropriate type, then you can call Invoke on it.

这篇关于使用运行时类型执行的泛型方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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