如何获得与Type.GetType(字符串)嵌套类的类型 [英] how to get type of nested class with Type.GetType(string)

查看:229
本文介绍了如何获得与Type.GetType(字符串)嵌套类的类型的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我可以创建一个新的类像 Namespace.OuterClass.NestedClass 一个完全合格的名称。但是,试图获得与 Type.GetType(Namespace.OuterClass.NestedClass)收益的类型。下面是示例代码:

I can create a new class with a fully qualified name like Namespace.OuterClass.NestedClass. But attempting to get the type with Type.GetType("Namespace.OuterClass.NestedClass") returns null. Here is sample code:

namespace Sample
{
   public class Program
   {
      public class Animal { }
      public class Vegetable { }
      public class Mineral { }

      static public void Test()
      {
         Object o = new Sample.Program.Vegetable();
         Type t = Type.GetType("Sample.Program.Vegetable"); // returns null
         Console.ReadKey();
      }

      static void Main(string[] args)
      {
         Program.Test();
      }
   }
}



如何使用 Type.GetType 的嵌套类?

推荐答案

C#的完全合格的字符串值名称使用 + 类之间。与 Type.GetType(Namespace.OuterClass + NestedClass)获得通过字符串类型。

String values for C# fully qualified names use + between classes. Get the type by string with Type.GetType("Namespace.OuterClass+NestedClass").

Type.GetType MSDN文档(字符串) 给语法表各种类型(泛型类型,参数,非托管指针等),包括父类和嵌套类。

MSDN documentation for Type.GetType(string) gives a syntax table for various types (generic types, arguments, unmanaged pointers, etc.) including "parent class and a nested class".

添加这些线路的问题的样本代码:

Adding these lines to the question's sample code:

string typeName1 = typeof(Sample.Program.Vegetable).FullName;
string typeName2 = typeof(Vegetable).FullName;



将证明字符串类型名称等于 Sample.Program +蔬菜

ECMA- 335 分区IV的相关CLILibrary.xml提供此约定明确的细节。在 Type.GetType(字符串)语法ECMA-335表是相同的MSDN文档中使用。

ECMA-335 Partition IV's associated CLILibrary.xml provides the definitive details for this convention. The Type.GetType(string) syntax table in ECMA-335 is identical to that used in the MSDN documentation.

这篇关于如何获得与Type.GetType(字符串)嵌套类的类型的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆