2015-10-07 148 views
0

我有一个项目在MVC C#code-first。我想将一个类型传递给我的方法。我的方法需要一个班才能工作。但我不想通过一门课 - 我希望它是动态的。有没有可能?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 
     } 
    } 
+2

的可能的复制[如何使用反射来调用泛型方法?(http://stackoverflow.com/questions/232535/how-to-use-reflection-to-call-generic-method) – kai

+0

是的,可能是一样的。但我的表名是动态的。我怎样才能转换或如何使用反射来创建字符串表名称到真正的类传递给LINQDynamic <这里是我想要动态类>。 –

回答

0

反思例如:

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

看来,你是不是在你的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); 
0

我以前遇到同样的问题。这通常是我所做的。保持在代码中调用堆栈的方式,直到您可以描述接口发生的事情而不是泛型,即: IEnumerable GetResults(字符串项)。

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

虽然轻轻一点。在并发和长时间运行的应用程序(如Web应用程序)中很容易遇到多线程,内存泄漏和其他令人讨厌的问题。我几乎建议你不要这样做。

0

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