为了保持简洁,我可以这样做:
UIRvWindow AppWin = new UIRvWindow();
UITestControl path = new UITestControl();
path = AppWin.UnderlyingClass1.UnderLyingClass2;
IEnumerable<WpfButton> collection = path.GetChildren().OfType<WpfButton>();
foreach(WpfButton button in collection)
{
System.Diagnostics.Trace.WriteLine(button.FriendlyName + " - " + button.DisplayText + " - " + button.Name + " - " + button.AutomationId);
}
这很好,但我希望能够做到这一点:
UIRvWindow AppWin = new UIRvWindow();
UITestControl path = new UITestControl();
string x = "AppWin.UnderlyingClass1.UnderLyingClass2";
path = x;
IEnumerable<WpfButton> collection = path.GetChildren().OfType<WpfButton>();
foreach(WpfButton button in collection)
{
System.Diagnostics.Trace.WriteLine(button.FriendlyName + " - " + button.DisplayText + " - " + button.Name + " - " + button.AutomationId);
}
基本上,我有一个字符串列表,我想逐个运行它们。有没有办法做到这一点?
答案 0 :(得分:0)
反射是一种实现动态调用的方法。假设您有一个类型名称列表作为字符串,那么您可以执行以下操作:
List<string> classes = new List<string> { "WindowsFormsApplication1.MyClass1", "WindowsFormsApplication1.MyClass2" };
foreach (var typeName in classes)
{
Type type = Type.GetType(typeName);
var instance = Activator.CreateInstance(type);
var result = (type.GetMethod("GetChildren").Invoke(instance, null) as IEnumerable<object>).OfType<WpfButton>();
}
如果您的所有类都继承自其中包含虚拟GetChildren()
方法的基类,那么您可以减少一点反射,如下所示:
foreach (var typeName in classes)
{
Type type = Type.GetType(typeName);
var instance = Activator.CreateInstance(type);
IEnumerable<WpfButton> myButtons = null;
if(instance is MyBase) //MyBase is base class having virtual GetChildren() and this base class is derived by MyClass1, MyClass2...
{
myButtons = (instance as MyBase).GetChildren().OfType<WpfButton>();
}
}
如果您计划使用太多类型的PS反射可能会出现性能问题,请谨慎使用并正确设计目标。
希望这能帮到你......