C# - 将Reflection.PropertyInfo对象转换为其Type

Ran*_*der 5 c# reflection

在我的应用程序中,我有一个Reflection.PropertyInfo名为'property' 的变量.当我这样做时property.GetValue(myObject,null),价值是Master.Enterprise.Enterprise是我的应用程序中的一个类.因此,'property'包含对我的应用中的类的引用.

在运行时,我想以某种方式将'property'转换为它的type(Master.Enterprise),所以我可以使用它,就像它是类类型一样.

我知道这可以做到,因为当我查看调试器中的代码时,调试器正确地将'property'转换为它引用的类型,并且我可以在调试器中看到Enterprise类的所有属性.

我该怎么做呢?

Jus*_*tin 5

听起来像你需要定义一个接口 - 然后你可以要求你的属性返回一个实现该接口的对象,然后你就可以转换到该接口,而不管是哪个类实现了该接口:

IEnterprise enterprise = (IEnterprise)property.GetValue(myObject, null);
Run Code Online (Sandbox Code Playgroud)

您拥有的唯一选择是使用反射在返回的对象上调用方法和属性 - 这是visual studio调试器正在执行的操作.


Mic*_*l G 1

如果您有类型名称的字符串,您可以执行以下操作:

Assembly execAsm = Assembly.GetExecutingAssembly();
object instance = AppDomain.CurrentDomain.CreateInstanceAndUnwrap(execAsm.FullName, "RipperWorkbench.Classes.LoadManager"); // the type name cam come from a variable or someplace else.
Run Code Online (Sandbox Code Playgroud)

然后你可以将其转换为你需要的类型

Master.Enterprise ent = obj as Master.Enterprise;
if (obj != null) 
{
     ...
}
Run Code Online (Sandbox Code Playgroud)

或者,让对象实现一个接口:您必须确保该类型已加载到当前 AppDomain 中,否则无法反映该类型。

Assembly asm = Assembly.GetExecutingAssembly();

// The executing assembly can change also; so you can load types from other assemblies
// use this if the type isn't loaded in this AppDomain yet.
//Assembly asm = Assembly.LoadFile("path to assembly here", new Evidence());

String typeToLoad = "Master.Enterprise"; // this can be from a config or database call
Type objType = asm.GetType(typeToLoad, true);

if (!objType.IsPublic)
return null;

// make sure the type isn't Abstract
if (((objType.Attributes & TypeAttributes.Abstract) == TypeAttributes.Abstract))
    return null;

// IEnterprise is the interface that all of the plugin types must implement to be loaded
Type objInterface = objType.GetInterface("IEnterprise", true);

if (objInterface == null)
    return null;

    var iri = (IEnterprise)Activator.CreateInstance(objType);
    return iri;
Run Code Online (Sandbox Code Playgroud)