【发布时间】:2013-03-21 16:32:14
【问题描述】:
是否可以从 Dynamic 或 Object 转换为变量类型?目标变量类型是一个泛型类,只是具体数据类型不同。
我正在寻找抽象的解决方案,但情况是这样的:我想要一个针对不同实体的 Linq2SQL 命令 - 我可以 GetProperty + GetValue 的 EntityFramework 上下文,但是必须将它转换为一些确切的类型,但是这些来自变量输入 - 数据库表的名称。
我所拥有的示例:
Type NewType = typeof(System.Data.Objects.ObjectSet<>);
NewType.MakeGenericType(new Type[] {"...some type here that's variable accordint to user input - like Person, Address, Contact, ..."});
Object MyObject = Context.GetType().GetProperty("the same variable like above - Person, Address,...", BindingFlags.Public | BindingFlags.Instance).GetValue(Context, null); // this is EntityFramework Context
我需要但不知道怎么做的例子:
NewType CastedObject = (NewType) MyObject;
// or
NewType CastedObject = Convert.ChangeType(MyObject, NewType);
// or
NewType CastedObject = MyObject as NewType;
所以我可以这样做:
(from x in CastedObject where x.ID == ID select x).FirstOrDefault();
对于那些熟悉 PHP 的人,我正在尝试这样做:
(from x in Context.$tablename where x.ID == ID select x).FirstOrDefault();
【问题讨论】:
-
我已经编辑了你的标题。请参阅“Should questions include “tags” in their titles?”,其中的共识是“不,他们不应该”。
标签: c# dynamic reflection