我有以下方法用于遍历可视树以查找类型的所有对象:
public static IEnumerable<T> FindVisualChildren<T>(DependencyObject depObj) where T : DependencyObject
{
if (depObj != null)
{
for (int i = 0; i < VisualTreeHelper.GetChildrenCount(depObj); i++)
{
DependencyObject child = VisualTreeHelper.GetChild(depObj, i);
if (child != null && child is T)
{
yield return (T)child;
}
foreach (T childOfChild in FindVisualChildren<T>(child))
{
yield return childOfChild;
}
}
}
}
问题是Type是一个存储在veriable中的字符串值。传递类似以下类型时,使用Above可以正常工作:
var x = FindVisualChildren<TextBox>(this);
然而在我的情况下,TextBox是一个存储在变量中的字符串,我们将调用item。所以我想做这样的事情:
var item = "TextBox";
var x = FindVisualChildren<item>(this);
但Item不是一种类型。那么获取Sting变量类型的最佳方法是什么,以便将其传递给我的方法。变量将是TextBox,TextBlock,Grid,StackPanel,DockPanel或TabControl。现在我在Switch语句中拥有所有内容并且它正在运行,但希望以更简洁的方式执行相同的操作。
答案 0 :(得分:0)
如评论中所述,您需要使用反射。
首先,您需要获取要使用的Type
。
你可以用两种方式做到这一点。您可以从指定类型名称的字符串创建Type
,如下所示:
var type_name = "System.Windows.Controls.TextBox, PresentationFramework, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35";
var type = Type.GetType(type_name, true);
或者您可以直接定义类型:
var type = typeof (TextBox);
然后你需要使用反射来获得这样的MethodInfo
:
var method = typeof (StaticClass).GetMethod("FindVisualChildren", BindingFlags.Static | BindingFlags.Public);
其中StaticClass
是包含FindVisualChildren
方法的静态类的名称。
然后你可以调用这样的方法:
IEnumerable result = (IEnumerable)method.MakeGenericMethod(type).Invoke(null, new object[] { this});
请注意,我投靠IEnumerable
而不是IEnumerable<T>
。