【问题标题】:Get an inner class via reflection (Windows 8.1)通过反射获取内部类(Windows 8.1)
【发布时间】:2026-01-20 08:10:01
【问题描述】:

我有一个名为Languages 的课程。它包含其他几个静态类。例如:

namespace TryReflection
{
    class Languages
    {
        public static class it
        {
            public static string PLAY = "Gioca";
            public static string START = "Inizia!";
            public static string NEXT = "Prossimo";
            public static string STOP = "Ferma!";
            public static string SCORE = "Punti";
            public static string RESTART = "Per cambiare la difficoltà inizia una nova partita";
        }

        public static class en
        {
            public static string PLAY = "Play";
            public static string START = "Start!";
            public static string NEXT = "Next";
            public static string STOP = "Stop!";
            public static string SCORE = "Score";
            public static string RESTART = "To change difficulty restart your match";
        }
    }
}

每个类都包含一些静态字符串。我想通过反射(以及我拥有的系统语言字符串)访问这些类。我可以通过这种方式访问​​Languages 类:

Type tt = Type.GetType("TryReflection.Languages", true); 

然后我想做类似的事情:

tt.GetNestedType();

不幸的是,在 Windows 8.1 上似乎没有 GetNestedTypes 方法。那么,我怎样才能访问这些类之一?谢谢。

【问题讨论】:

  • 如果您打算使用它来本地化您的应用程序,那么您不是按照标准方式进行的。使用资源文件和内置的本地化库关注Microsoft's guidelines
  • 您使用哪个 .net 框架版本?我对Windows Phone一无所知,但如果我知道该版本,也许我可以为您找到解决方法。还有更好的方法来做你想做的事情,你对建议感兴趣吗?
  • WinRT 使反射有点,呃,哥特式。您必须改用 TypeInfo.DeclaredNestedTypes。

标签: c# reflection windows-phone-8.1 windows-8.1 win-universal-app


【解决方案1】:

@D Stanley 是正确的。应该以不同的方式处理本地化。

但是,要回答您的问题,请查看 PropertyDescriptor 类。它允许您获取类属性的抽象。我使用它来迭代集合以使用属性和值构建 DataTables。

//Get the properties as a collection from the class
Type tt = Type.GetType("TryReflection.Languages", true);
PropertyDescriptorCollection props = TypeDescriptor.GetProperties(tt);  

for (int i = 0; i < props.Count; i++)
{
    PropertyDescriptor prop = props[i];
    string propertyInfo = String.Format("{0}: {1}", 
        prop.Name, 
        prop.PropertyType.GetGenericArguments()[0]));

    Console.Out.Write( propertyInfo );
}

【讨论】: