[英]How to assign a value to a static field dynamically create objects?
我想使用反射类PropertyCondition(in assembly UIAutomationClient.dll)
创建一个对象。 为了获得所需的类构造函数,我使用以下代码:
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) });
但是如何传递构造函数AutomationElement.AutomationIdProperty
?
谢谢。
我相信automationId
是一个字符串属性 。 您需要的是找到接受strings
constructor
:
ConstructorInfo ctor = propertyConditionType.GetConstructor(new[] { typeof(string) });
object instance = ctor.Invoke(new object[] { automationId });
或者您可以使用Activator.CreateInstance方法 :
CreateInstance(AppDomain,String,String,Boolean,BindingFlags,Binder,Object [],CultureInfo,Object [])
使用命名的程序集和最匹配指定参数的构造函数,创建其名称在指定的远程域中指定的类型的实例。
您缺少的步骤是一个简单的FieldInfo.GetValue
调用,要获取必须传递到构造函数中的值。 我重组了您的代码:
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.