【发布时间】:2009-05-25 20:01:50
【问题描述】:
我需要动态地将一个属性转换为它的实际类型。我如何/可以使用反射来做到这一点?
解释一下我正在研究的真实场景。我正在尝试在实体框架属性上调用“First”扩展方法。要在框架上下文对象上调用的特定属性作为字符串传递给方法(以及要检索的记录的 id)。所以我需要对象的实际类型才能调用 First 方法。
我不能在对象上使用“Where”方法,因为 lambda 或委托方法仍然需要对象的实际类型才能访问属性。
由于对象是由实体框架生成的,我无法将类型转换为接口并对其进行操作。
这是场景代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Reflection;
namespace NmSpc
{
public class ClassA
{
public int IntProperty { get; set; }
}
public class ClassB
{
public ClassA MyProperty { get; set; }
}
public class ClassC
{
static void Main(string[] args)
{
ClassB tester = new ClassB();
PropertyInfo propInfo = typeof(ClassB).GetProperty("MyProperty");
//get a type unsafe reference to ClassB`s property
Object property = propInfo.GetValue(tester, null);
//get the type safe reference to the property
ClassA typeSafeProperty = property as ClassA;
//I need to cast the property to its actual type dynamically. How do I/Can I do this using reflection?
//I will not know that "property" is of ClassA apart from at runtime
}
}
}
【问题讨论】:
-
如何将其转换为您不知道的类型?你在运行时就知道了。所以只能作为对象来处理。
-
你能解释一下你的场景吗?假设有一种方法可以动态执行(实际上没有,但是……)接下来你会用这个变量做什么?你不能调用 .IntProperty 因为你不知道它的类型,所以回到开头没有必要将它转换为 ClassA。您只需继续反射以获取 IntProperty 等等......
-
强制转换在很大程度上是编译时的事情,而不是真正的反射事情。您究竟是什么意思,“将属性转换为实际类型”?有一些涉及泛型的选项,但如果没有明确的想法你想要实现什么,很难给出一个好的答案。即使使用泛型(通过
MakeGenericMethod等),您也只需将其作为T- 但这实际上并不能让您做 很多......所以:你怎么办想要做,一旦你输入它... -
你能澄清你的问题吗?因为我无法正确理解。
-
框架中没有真正的动态转换。通常,此类问题可以使用接口或泛型来解决。
标签: c# entity-framework reflection