在 wpf-Application 中,我想將 Panel 的子元素轉換為相應的元素型別。例如,一個 UIElementCollection 有 3 個子項: TextBox Button Label
如果我迭代 UIElementCollection 我將得到一個 UIElement 并且必須將每個元素都轉換為它的型別,然后才能使用它。
所以我嘗試使用一個通用方法,它將 UIElement 轉換為它的真實型別:
public static T getCastTo<T>(UIElement ele)
{
return (T) (object) ele;
}
通過呼叫使用它
TextBox tb = SomeGenerics.getCastTo<TextBox>(ele);
正如預期的那樣給了我一個文本框。
我現在想做的是在一個回圈中使用它,比如
foreach(UIElement ele in uielementCollection) {
SomeGenerics.getCastTo<ele.GetType()>(ele); // or
SomeGenerics.getCastTo<typeof(ele)>(ele);
}
但編譯器告訴我不能將變數用作型別。有沒有辦法在不“手動”指定型別的情況下使用通用方法?
uj5u.com熱心網友回復:
只需使用Enumerable.Cast(硬鑄)或Enumerable.OfType(也過濾器):
IEnumerable<TextBox> allTextBoxes = uielementCollection.OfType<TextBox>();
通常,如果您在運行時知道型別,則不能使用泛型方法,泛型是編譯時功能。因此,您所能做的就是將它們轉換為所需的型別或通用基本型別。然后,您可以通過嘗試將它們轉換為特定型別來在其他地方處理它們:
foreach (Control c in uielementCollection)
{
switch (c)
{
case TextBox txt:
// handle TextBox
break;
case Label lbl:
// handle Label
break;
// ... and so on
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/423090.html
標籤:
