C# 是否将字符串转换为页面类型?

C# 是否将字符串转换为页面类型?,c#,windows-8,navigation,windows-store-apps,C#,Windows 8,Navigation,Windows Store Apps,我想将字符串DashBoard转换为名为DashBoard的页面类型,因为我想在导航中使用它。通常我导航到这样的页面 this.Frame.Navigate(typeof(DashBoard)); 但我想用这样的变量替换仪表板页面 this.Frame.Navigate(typeof(Somestring)); 如果您知道仪表板的完全限定名,即它所在的程序集和命名空间,则可以使用反射来确定传递给导航的内容 根据需要查看,尤其是GetTypes和GetExportedTypes。如果您知道仪表

我想将字符串DashBoard转换为名为DashBoard的页面类型,因为我想在导航中使用它。通常我导航到这样的页面

this.Frame.Navigate(typeof(DashBoard));
但我想用这样的变量替换仪表板页面

this.Frame.Navigate(typeof(Somestring));

如果您知道
仪表板的完全限定名,即它所在的程序集和命名空间,则可以使用反射来确定传递给
导航的内容


根据需要查看,尤其是
GetTypes
GetExportedTypes

如果您知道
仪表板的完全限定名,即它所在的程序集和命名空间,则可以使用反射来确定传递给
导航的内容


根据需要查看,尤其是
GetTypes
GetExportedTypes

您可以使用
Type.GetType(string)

阅读有关如何格式化字符串的备注部分

或者您可以使用反射:

using System.Linq;
public static class TypeHelper
{
    public static Type GetTypeByString(string type, Assembly lookIn)
    {
        var types = lookIn.DefinedTypes.Where(t => t.Name == type && t.IsSubclassOf(typeof(Windows.UI.Xaml.Controls.Page)));
        if (types.Count() == 0)
        {
            throw new ArgumentException("The type you were looking for was not found", "type");
        }
        else if (types.Count() > 1)
        {
            throw new ArgumentException("The type you were looking for was found multiple times.", "type");
        }
        return types.First().AsType();
    }
}
这可用于以下情况:

private void Button_Click(object sender, RoutedEventArgs e)
{
    this.Frame.Navigate(TypeHelper.GetTypeByString("TestPage", this.GetType().GetTypeInfo().Assembly));
}

在这个例子中。该函数将在当前程序集中搜索名为TestPage的页面,然后导航到该页面。

您可以使用
Type.GetType(string)

阅读有关如何格式化字符串的备注部分

或者您可以使用反射:

using System.Linq;
public static class TypeHelper
{
    public static Type GetTypeByString(string type, Assembly lookIn)
    {
        var types = lookIn.DefinedTypes.Where(t => t.Name == type && t.IsSubclassOf(typeof(Windows.UI.Xaml.Controls.Page)));
        if (types.Count() == 0)
        {
            throw new ArgumentException("The type you were looking for was not found", "type");
        }
        else if (types.Count() > 1)
        {
            throw new ArgumentException("The type you were looking for was found multiple times.", "type");
        }
        return types.First().AsType();
    }
}
这可用于以下情况:

private void Button_Click(object sender, RoutedEventArgs e)
{
    this.Frame.Navigate(TypeHelper.GetTypeByString("TestPage", this.GetType().GetTypeInfo().Assembly));
}

在这个例子中。该函数将在当前程序集中搜索名为TestPage的页面,然后导航到该页面。

我不完全确定您的意思,但反射可能是您所追求的。实际上,我想将字符串转换为页面类型..这样我就可以在导航方法中直接使用字符串变量..因为我的字符串包含我必须导航的页面的名称,所以反射正是您所需要的。如果您想要隐式转换,您需要扩展DashBoard并自己实现它,但最终它仍然会使用反射。我不完全确定您的意思,但反射可能是您所追求的。实际上,我想将字符串转换为页面类型..这样我就可以在导航方法中直接使用字符串变量..因为我的字符串包含我必须导航的页面的名称,所以反射正是您所需要的。如果您想要隐式转换,您需要扩展DashBoard并自己实现它,但最终它仍然会使用反射。