2016-09-14 66 views
0

爲了保持簡潔,我可以這樣做:鑄造字符串UITestControl

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

你可能想標記這裏使用的語言 – pcnate

+0

發佈示例代碼:AppWin.UnderlyingClass1.UnderLyingClass2'會有幫助。 嘗試加載反射? –

回答

0

反射是一種實現動態調用的方式。假設你的類型名稱作爲字符串列表,那麼你可以做一些類似以下內容:如果所有的類都從具有它的虛擬GetChildren()方法的基類繼承

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>(); 

} 

,那麼你就可以減少一點如下反思:

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反射可能有性能問題,如果你打算使用過的種類太多,請謹慎和適當的設計目標使用它。 希望這對你有所幫助...