2012-02-24 208 views
3

我有一个小控制台应用程序,我正在修补,只是为了学习新的东西。为什么System.Type.IsPublic返回false?

在下面的代码,在Console.WirteLine(),如果我测试t.IsAbstract,或t.IsSealed,我的输出分别是AbstractClass true,或SealedClass 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 { } 
    } 
} 

回答

5

因为它们嵌套的Test内。

the documentation:如果Type被声明为public并且不是嵌套类型,则返回true;否则,是错误的。

正如@杰布的回答和文档建议,typeof(PublicClass)应该有值true为IsNestedPublic财产

+0

我的+1分析是错误的,克里斯答案是正确的 – JaredPar 2012-02-24 18:52:26

相关问题