c# - 为什么 System.Type.IsPublic 返回为 false?

标签 c# reflection

我有一个小的控制台应用程序,我正在修改它只是为了学习一些新东西。

在下面的代码中,在 Console.WirteLine() 中,如果我测试 t.IsAbstractt.IsSealed,我的输出分别是 AbstractClass trueSealedClass true。如我所料,所有其他人都返回 false

但是,如果我测试 t.IsPublic,所有内容,包括 PublicClassPublicInterface 都会返回 false这是为什么?

using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;

namespace ConsoleApplication1
{
    class Test
    { 
        static void Main(string[] args)
        {    
            Assembly assembly = Assembly.GetExecutingAssembly();
            Type[] assemblyTypes = assembly.GetTypes();
            foreach (Type t in assemblyTypes)
                Console.WriteLine(t.Name + " " + t.IsPublic);
            Console.ReadKey();
        }

        private class PrivateClass { }

        public class PublicClass { }

        protected class ProtectedClass { }

        sealed class SealedClass { }

        abstract class AbstractClass { }

        interface myInterface { }

        public interface PublicInterface { }
    }
}

最佳答案

因为它们嵌套在 Test 中。

来自 the documentation : 如果类型声明为公共(public)且不是嵌套类型,则为真;否则为假。

正如@Jeb 的回答和文档所建议的那样,typeof(PublicClass) 对于 IsNestedPublic 的值应该为 true属性

关于c# - 为什么 System.Type.IsPublic 返回为 false?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9436233/

相关文章:

c# - 修改枚举值的扩展方法

c# - 使用对象列表构建树

c# - Microsoft.SqlServer.Management.Smo 获取 SQL Server 的恢复模型

java - 使用反射访问DialogFragment中的一些字段

java - 如何利用反射满足工厂模式中的开闭原则?

java - 接口(interface)方法引用的注释信息

c# - Visual Studio 不断崩溃

c# - 如何在 Xamarin C# 中更改字体/颜色/大小

java - 检查方法是否需要使用注释的参数并反射(reflect)

java - 检索 Activity 实例的 ActivityInfo