简体   繁体   English

C#泛型与反射

[英]C# Generics and Reflection

i'm using linq. 我正在使用linq。 All my queries looks like var query = dc.GetTable<myType>() . 我所有的查询看起来像var query = dc.GetTable<myType>()

I wish i could choose "myType" using a string parameter. 我希望我可以使用字符串参数选择“ myType”。 I tried to create a Type object using reflection, but the compiler doesn't recognize Type objects as class definitions. 我尝试使用反射创建Type对象,但是编译器无法将Type对象识别为类定义。

Any suggestions? 有什么建议么? Thanks 谢谢

有一个GetTable(Type)扩展方法,它可以完全满足您的需求:

var query = dc.GetTable(Type.GetType("namespace.type, assembly"));

Why do you want that ? 你为什么要那个? Using the generic method like you do now, gives you compile time checking support, whereas a string parameter not. 像现在一样使用通用方法,可以为您提供编译时检查支持,而不能提供字符串参数。

You can create an query instance as a generic Table<> object, but it won't be recognized in compile time. 您可以将查询实例创建为通用Table <>对象,但在编译时将无法识别它。 see Using Type objects as Type Parameters for Generics in C# 请参见在C#中将类型对象用作泛型的类型参数

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM