如果只在运行时知道类型参数,如何调用泛型方法? [英] How do you call a generic method if you only know the type parameter at runtime?

查看:111
本文介绍了如果只在运行时知道类型参数,如何调用泛型方法?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这个方法:

I have this method:

public List<T> SomeMethod<T>( params ) where T : new()

所以我想调用这个<$

So I want to call this SomeMethod which is fine if I know the type:

SomeMethod<Class1>();

但是如果我在运行时只有 Class1 我无法调用它?

But if I only have Class1 at runtime I'm unable to call it?

那么如何调用带有未知T类型的 SomeMethod

So how to call SomeMethod with unknown T type? I got Type by using reflection.

我有Type的类型,但是 SomeMethod< Type | GetType()> 不起作用。

I have the Type of type but SomeMethod<Type | GetType()> doesn't work.

更新7. May:

以下是我想实现的示例代码:

Here is a sample code of what I want to achieve:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Reflection;

namespace ConsoleApplication63
{
    public class DummyClass
    {
    }

    public class Class1
    {
        public string Name;
    }

    class AssemblyTypesReflection
    {
        static void Main(string[] args)
        {
            object obj = new Class1() { Name = "John" } ;

            Assembly assembly = Assembly.GetExecutingAssembly();
            var AsmClass1 = (from i in assembly.GetTypes() where i.Name == "Class1" select i).FirstOrDefault();


            var list = SomeMethod<AsmClass1>((AsmClass1)obj); //Here it fails
        }

        static List<T> SomeMethod<T>(T obj) where T : new()
        {
            return new List<T> { obj };
        }
    }
}

这是一个演示。

This is a demo taken out of a bigger context.

推荐答案

您需要使用反射来调用它:

You need to call it using reflection:

var method = typeof(SomeClass).GetMethod("SomeMethod");
method.MakeGenericMethod(someType).Invoke(...);

这篇关于如果只在运行时知道类型参数,如何调用泛型方法?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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