c#类型为泛型类

本文关键字:泛型类 类型 | 更新日期: 2023-09-27 18:16:17

我有一个MVC c#代码项目。我想传递一个类型给我的方法。我的方法需要一个类来工作。但我不想传递一个类,我希望它是动态的。这可能吗?

这是我的代码;

string item ="PERSON" // item is a parametric I give the table name to get the type of table 
Assembly asm = Assembly.Load("ProjectName");
Type entityType = asm.GetType(String.Format("NameSpace.Model.{0}", item));
 var test = LINQDynamic<>.GetQueryResult(ssa,entityType,ddd); // In LINQDynamic<> I want to use entityType like that LINQDynamic<entityType> but it's not acceptable what can I make the convert type to generic?..Because table name is parametric.Is it possible to convert that type?
public class LINQDynamic<TEntity> where TEntity: class
   {
       public static object GetQueryResult(object pkKey,Type type, params object[] pkKeys)
       {
                     //TODO
       }
    }

c#类型为泛型类

反射示例:

public static void Main(string[] args)
{
    Type t = typeof(string);
    Type fooType = typeof(Foo<>);
    Type genericFooType = fooType.MakeGenericType(t);
    object o = Activator.CreateInstance(genericFooType,null);
    MethodInfo method = genericFooType.GetMethod("Bar");
    method.Invoke(o, null);
}
public class Foo<T> where T:class
{
    public void Bar()
    {
        Console.WriteLine ("Calling Bar");
    }
}

似乎您没有在LINQDynamic类中使用TEntity -而是将类型作为参数传递。这使得TEntity有点毫无意义。

试题:

public class LINQDynamic
{
   public static object GetQueryResult(object pkKey,Type type, params object[] pkKeys)
   {
                 //TODO
   }
}
var test = LINQDynamic.GetQueryResult(ssa,entityType,ddd);

我以前遇到过同样的问题。这是我通常做的。在你的代码中不断地缠绕调用堆栈,直到你可以描述接口而不是泛型发生了什么,即;IEnumerable GetResults(string item).

然后,使用表达式树生成方法的内容(这允许您保留泛型方法调用),并将编译后的lambda存储在静态字典中,其中键是您的"item",值是Func >。

小心行事。在并发和长时间运行的应用程序(如web应用程序)中,很容易遇到多线程、内存泄漏和其他严重问题。我几乎建议你不要这样做。

根据singsuyash的建议改编:

  object[] newobj = { pkey,entityType,pKyes };
            object[] parameters = new object[] { newobj };
            Type t = typeof (string);
            Type linqType = typeof (LinqDynamic<>);
            Type genericLinqType = linqType.MakeGenericType(entityType);
            object o = Activator.CreateInstance(genericLinqType, null);
            MethodInfo method = genericLinqType.GetMethod("GetEntityByPrimaryKey");
            var results = method.Invoke(o, parameters);