将 UIElementCollection 中的元素转换为相应元素的类型
Cast elements in UIElementCollection to Type of respective element
在 wpf-Application 中,我想将面板的 child 元素转换为相应的元素类型。
例如,一个 UIElementCollection 有 3 children:
文本框
按钮
标签
如果我迭代 UIElementCollection,我将得到一个 UIElement,并且必须先将每个元素转换为它的类型,然后才能使用它。
所以我尝试使用通用方法,将 UIElement 转换为其真实类型:
public static T getCastTo<T>(UIElement ele)
{
return (T) (object) ele;
}
通过调用
来使用它
TextBox tb = SomeGenerics.getCastTo<TextBox>(ele);
按预期给了我一个 TextBox。
我现在想做的是在类似
的循环中使用它
foreach(UIElement ele in uielementCollection) {
SomeGenerics.getCastTo<ele.GetType()>(ele); // or
SomeGenerics.getCastTo<typeof(ele)>(ele);
}
但是编译器告诉我不能将变量用作类型。
有没有一种方法可以在不“手动”指定类型的情况下使用泛型方法?
只需使用Enumerable.Cast
(强制转换)或Enumerable.OfType
(也有过滤器):
IEnumerable<TextBox> allTextBoxes = uielementCollection.OfType<TextBox>();
一般来说,如果您在运行时知道类型,则不能使用泛型方法,泛型是一种编译时功能。所以你所能做的就是将它们转换为所需的类型或公共基类型。然后你可以在其他地方通过 try-casting 将它们处理成特定类型:
foreach (Control c in uielementCollection)
{
switch (c)
{
case TextBox txt:
// handle TextBox
break;
case Label lbl:
// handle Label
break;
// ... and so on
}
}
在 wpf-Application 中,我想将面板的 child 元素转换为相应的元素类型。 例如,一个 UIElementCollection 有 3 children: 文本框 按钮 标签
如果我迭代 UIElementCollection,我将得到一个 UIElement,并且必须先将每个元素转换为它的类型,然后才能使用它。
所以我尝试使用通用方法,将 UIElement 转换为其真实类型:
public static T getCastTo<T>(UIElement ele)
{
return (T) (object) ele;
}
通过调用
来使用它TextBox tb = SomeGenerics.getCastTo<TextBox>(ele);
按预期给了我一个 TextBox。
我现在想做的是在类似
的循环中使用它foreach(UIElement ele in uielementCollection) {
SomeGenerics.getCastTo<ele.GetType()>(ele); // or
SomeGenerics.getCastTo<typeof(ele)>(ele);
}
但是编译器告诉我不能将变量用作类型。 有没有一种方法可以在不“手动”指定类型的情况下使用泛型方法?
只需使用Enumerable.Cast
(强制转换)或Enumerable.OfType
(也有过滤器):
IEnumerable<TextBox> allTextBoxes = uielementCollection.OfType<TextBox>();
一般来说,如果您在运行时知道类型,则不能使用泛型方法,泛型是一种编译时功能。所以你所能做的就是将它们转换为所需的类型或公共基类型。然后你可以在其他地方通过 try-casting 将它们处理成特定类型:
foreach (Control c in uielementCollection)
{
switch (c)
{
case TextBox txt:
// handle TextBox
break;
case Label lbl:
// handle Label
break;
// ... and so on
}
}