外部派生类是否通过从父级继承的内部类的 C#.NET 反射可见



在下面的代码示例中,我想从类 A 继承类 B,如果我只有类型 B.AC 的对象,则能够获取类 B 的名称。

所以我的主题问题可以指定为:B 类是否通过 C#.NET 反射可见 B.AC?

基于公认的答案 - 答案是"否",我必须在 B 中声明new class AC并从 A.AC 派生。

using System;
namespace Question{
    class Program{
        class A{
           public class AC{}
        }
        class B: A{
           //new public class AC:A.AC{} // work around to get B+AC
        }
        class D: A{
           new public class AC:A.AC{} // work around to get D+AC
           public class DAC:A.AC{} // just another example
        }
        static void Main(string[] args)
        {
            var b_ac = new B.AC{}.GetType();
            var B_AC = typeof(B.AC);
            var D_AC = typeof(D.AC);
            var DAC = typeof(D.DAC);
            Func<Type,string> enclosure = (x)=>{
                Console.WriteLine(x.DeclaringType.Name);  // gives A - wrong
                Console.WriteLine(x.BaseType.Name);  // gives Object - wrong
                Console.WriteLine(x.FullName);  // gives A+AC - wrong, I want B+AC
                Console.WriteLine(x.ReflectedType.FullName);  // gives A - wrong
                return "B"; // I want to get name of class B through reflection
            };
           Console.WriteLine(enclosure(b_ac)); // gives A+AC - wrong, see details above
           Console.WriteLine(enclosure(B_AC)); // gives same wrong
           Console.WriteLine(enclosure(D_AC)); // gives D+AC - good
           Console.WriteLine(enclosure(DAC)); // gives D+DAC - good
           Console.ReadKey();
         }
    }
}

是的,您必须使用new重新定义 AC 才能执行此操作。如果您使用 ILSpy 之类的东西查看反射的代码,您会发现它实际上是在构造行var b_ac = new B.AC{}.GetType(); newobj instance void Question.Program/A/AC::.ctor()。它调用A中定义的构造函数,就好像您已经完成了new A.AC{}.GetType()一样。

最新更新