【发布时间】: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#