简体   繁体   English

如何为静态字段分配值动态创建对象?

[英]How to assign a value to a static field dynamically create objects?

I want to create an object using reflection class PropertyCondition(in assembly UIAutomationClient.dll) . 我想使用反射类PropertyCondition(in assembly UIAutomationClient.dll)创建一个对象。 In order to obtain the desired class constructor, I use the following code: 为了获得所需的类构造函数,我使用以下代码:

var assembly = AppDomain.CurrentDomain.GetAssemblies().First(x => x.FullName.Contains("AutomationClient"));

var propertyConditionType = assembly.DefinedTypes.First(x => x.Name == "PropertyCondition");
var automationElementType = assembly.DefinedTypes.First(x => x.Name == "AutomationElement");

var automationIdPropertyType = automationElementType.GetField("AutomationIdProperty").FieldType;
var constructor = propertyConditionType.GetConstructor(new Type[] { automationIdPropertyType, typeof(object) });

But how do I pass in constructor AutomationElement.AutomationIdProperty ? 但是如何传递构造函数AutomationElement.AutomationIdProperty

Thank you. 谢谢。

I belive that automationId is a string property . 我相信automationId是一个字符串属性 And what you need is find constructor which accepts strings : 您需要的是找到接受strings constructor

ConstructorInfo ctor = propertyConditionType.GetConstructor(new[] { typeof(string) });
object instance = ctor.Invoke(new object[] { automationId });

Or you can use Activator.CreateInstance Method : 或者您可以使用Activator.CreateInstance方法

CreateInstance(AppDomain, String, String, Boolean, BindingFlags, Binder, Object[], CultureInfo, Object[]) CreateInstance(AppDomain,String,String,Boolean,BindingFlags,Binder,Object [],CultureInfo,Object [])

Creates an instance of the type whose name is specified in the specified remote domain, using the named assembly and the constructor that best matches the specified parameters. 使用命名的程序集和最匹配指定参数的构造函数,创建其名称在指定的远程域中指定的类型的实例。

The step you are missing is a simple FieldInfo.GetValue call, to get the value you have to pass into the constructor. 您缺少的步骤是一个简单的FieldInfo.GetValue调用,要获取必须传递到构造函数中的值。 I restructured your code: 我重组了您的代码:

var automationIdPropertyField = automationElementType.GetField("AutomationIdProperty");

var automationIdPropertyType = automationIdPropertyField.FieldType;
var automationIdPropertyValue = automationIdPropertyField.GetValue(null);

var constructor = propertyConditionType.GetConstructor(new[] { automationIdPropertyType, typeof(object) });

var obj = constructor.Invoke(new[] {automationIdPropertyValue, ...});

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

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