我只想允许从特定方法调用该方法。看看下面的代码。
private static void TargetMethod()
{
}
private static void ForbiddenMethod()
{
TargetMethod();
}
private static void AllowedMethod()
{
TargetMethod();
}
我只需要AllowedMethod 就可以调用TargetMethod。如何使用 System.Security.Permissions
中的类来做到这一点?
更新:感谢您的回答,但我不想讨论我的应用程序的设计。我只想知道是否可以使用 .net 安全性来做到这一点?
最佳答案
您可以使用普通的面向对象设计来解决这个问题。将 AllowedMethod
移动到一个新类,并使 ForbiddenMethod
成为该类的私有(private)方法:
public class MyClass
{
public void AllowedMethod() { // ... }
private void TargetMethod() { // ... }
}
AllowedMethod 可以访问私有(private)成员,但其他人没有。
关于c# - 如何禁止调用方法 C#,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2071338/