【问题标题】:C# Public vs. Internal in different assemblies [duplicate]不同程序集中的C#公共与内部[重复]
【发布时间】:2021-09-27 17:34:50
【问题描述】:

我有点困惑。

我知道 public 可以从任何地方访问,而内部类只能在程序集中访问。

但是我在我的代码中发现了一些奇怪的东西。

我在一个解决方案中拥有三个项目。 所有项目共享同一个命名空间。

项目 A(主要可执行文件)

namespace Everything 
{
   class Program 
   {
      void Main() 
      {
         Runner r = new();
      }
   }
}

项目 B(库类)

namespace Everything 
{
   public class Runner 
   {
      public Runner() 
      {
         // Loads external assembly in runtime and creates instance
         Assembly assembly = Assembly.Load("my.dll","my.pdb");
         Type type = assembly.GetType("Everything.InternalClass");
         Execute Instance = (Execute)Activator.CreateInstance(type);
      }
   }

   public class Execute
   {
       //something to do
   }
}

最后是 Project C (my.dll)(另一个类库)

namespace Everything 
{
   class InternalClass : Execute
   {
      // This is executed in correct way - even it is in different assembly and it is set as internal (by default)
   }
}

为什么它可以正常工作?我在想,我需要在我的项目 C 中使用 public - 因为它在不同的程序集中......

【问题讨论】:

  • 为什么你认为它不起作用?既然是internal?
  • 是的,没有钥匙就不能启动汽车,但是如果你要剥掉一些电线并绕过钥匙,好吧..
  • 那么,原因正如 Joey 在下面的评论中所说,反射绕过了可访问性修饰符?
  • 辅助功能修饰符主要用于编译时安全。当你使用反射时,护栏就消失了。查看副本。

标签: c#


【解决方案1】:

可访问性修饰符会影响类型和成员在普通 C# 代码中的可见位置。反射允许您绕过所有这些。您还可以通过反射等方式设置私有字段。

如果你想要一个普通的 C# 方式来访问内部类型,你可以使用InternalsVisibleTo attribute

【讨论】:

    【解决方案2】:

    GetType 返回您搜索的所有内容。如果要获取公共成员,请改用 GetExportedTypes。 通过反射,您可以查看和使用所有成员。

    【讨论】:

      猜你喜欢
      • 2013-11-29
      • 2010-10-17
      • 2016-02-27
      • 1970-01-01
      • 1970-01-01
      • 2012-10-28
      • 2016-12-27
      • 1970-01-01
      相关资源
      最近更新 更多