我有以下方法用于遍历可视化树以查找类型的所有对象:
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;
}
}
}
}
问题是类型是一个存储在可验证对象中的字符串值。当传递如下类型时,使用 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 语句中拥有所有内容并且它正在工作,但想要一种更简洁的方式来做同样的事情。
最佳答案
如评论中所述,您需要使用反射。
首先你需要获得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>
.
关于c# - 将字符串变量传递给泛型 <T>,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33503954/