通用方法使用运行时类型执行

Sar*_*rit 30 c# generics methods

我有以下代码:

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

    }
}
Run Code Online (Sandbox Code Playgroud)

现在,我知道我无法执行DoSomething()有没有其他方法可以使用此功能?

Chr*_*son 37

你可以,但它涉及反思,但你可以做到.

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

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


Max*_*erl 5

this.GetType().GetMethod("DoSomething").MakeGenericMethod(p.Value.GetType()).Invoke(this, new object[]{p.Name, p.Value});
Run Code Online (Sandbox Code Playgroud)

应该管用.