Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/329.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 通过反射在运行时实例化类_C#_Reflection - Fatal编程技术网

C# 通过反射在运行时实例化类

C# 通过反射在运行时实例化类,c#,reflection,C#,Reflection,您好,我正在尝试在运行时发现并实例化一个类。程序集加载到factory对象中 到目前为止,一切都很顺利 Object obj = Activator.CreateInstance( (factory.ProxyAssembly.GetType("tempuri.org.Authorizations"))); 但是我无法使用obj获取属性名,因为obj.FirstName或obj.LastName不可用,因此我正在尝试将其键入适当的基础类 但是下面给出的代码不起作用 factory.Pr

您好,我正在尝试在运行时发现并实例化一个类。程序集加载到factory对象中

到目前为止,一切都很顺利

Object obj = Activator.CreateInstance(
   (factory.ProxyAssembly.GetType("tempuri.org.Authorizations")));
但是我无法使用
obj
获取属性名,因为
obj.FirstName
obj.LastName
不可用,因此我正在尝试将其键入适当的基础类

但是下面给出的代码不起作用

 factory.ProxyAssembly.GetType("tempuri.org.Authorizations")
     .UnderlyingSystemType.BaseType a = 
         Activator.CreateInstance(factory.ProxyAssembly
              .GetType("tempuri.org.Authorizations").UnderlyingSystemType);
感谢您的帮助

tempuri.org.Authorizations a =  (tempuri.org.Authorizations)Activator.CreateInstance(factory.ProxyAssembly.GetType("tempuri.or g.Authorizations");
使用(类型)查看铸件。其中Type是返回的类类型。在这种情况下,类型是编译时的事情。反射使用抽象来屏蔽具体类型,但在这种情况下,您需要它。除非您使用DOE:

a.getClass().getField("FirstName").getString(a);

实例化对象后需要强制转换该对象。

您无法强制转换,因为您没有将程序集添加为项目中的引用。您需要使用反射来获取对象属性。使用Type.GetProperty和PropertyInfo.GetValue。请注意C#version 4 dynamic关键字如何大大减轻语法痛苦,推荐使用。

您不能将obj强制转换为授权吗?你到底想做什么,因为可能还有其他更好的方法来实现你的目标。到目前为止,我正在即时窗口中运行它。factory.ProxyAssembly.GetType(“tempuri.org.Authorizations”).UnderlyingSystemType.BaseType a=Activator.CreateInstance(factory.ProxyAssembly.GetType(“tempuri.org.Authorizations”).UnderlyingSystemType;预期表达式结束显示消息“预期表达式结束”@TJHeuvel我不知道类型授权。我是通过factory.ProxyAssembly.GetType(“tempuri.org.Authorizations”)找到它的。UnderlineingSystemType下面是@TJHeuvel的详细信息,我正在运行时基于wsdl文件为webservice代理创建一个程序集。我正在使用codedom提供程序。Web服务方法具有参数类型“Authorizations”。因此,在创建部件1之后。我想发现参数类型2。实例化它。3.分配值并将分配的参数发送到webservice代理。我不知道类型授权。我通过factory.proxysassembly.GetType(“tempuri.org.Authorizations”)找到了它。UnderlyingSystemType@Reflection新手,听起来你不需要一个强类型的对象。即使它是
对象
,也会有它的类型。您可以将它传递给使用反射接收它的任何方法。我还不知道它的类型,只知道它的名字。所以我不能用'tempuri.org.a'。这就是为什么我在作业左侧使用factory.ProxyAssembly.GetType(“tempuri.org.Authorizations”).underyingSystemType.BaseType a。谢谢。我还无法找到将类型转换为动态运行时类型的方法。感谢Hans,它与p=obj.GetProperty和p.SetValue()一起工作。