如何允许对方法的访问仅作为委托传递但不执行?

how to allow access to method to only be passed as a delegate but not executed?

我有一个私有方法,我想允许访问仅作为委托传递,但不以其他方式执行。

例如:

class a
{
   public delegate int myDelegate(int a);
   public static int myMethod(int data, myDelegate action)
   {
        //my code
   }

   private static int methodA(int a){ //code}
   private static int methodb(int a){ //code}
}

class b
{
   public void anotherMethod()
   {
       var doAction = new myDelegate(methodA);
       result = myMethod(8, doAction);
   }
}

所以在我的示例中,我希望 methodA 和 MethodB 仅在 classa 中执行,但仍然允许访问它们,因此它们可以用作传递给来自 [=20] 的方法的委托=] a.

有可能吗? 目前我收到一个错误 "methodA is inaccessible due to protection level"

如果我的理解正确,您想知道如何使用委托(传递操作/函数)作为参数吗?

如果是这样,那么您应该使用 Action<> and/or Func<>,因为它们是委托。那么您的代码可能如下所示:

    class a
    {
        public int myMethod(int data, Func<int, int> func)
        {
            return func.Invoke(data);
        }
    }

    class b
    {
        public void anotherMethod()
        {
            var classA = new a();
            var result = classA.myMethod(8, Double);
        }

        private int Double(int i)
        {
            return i * 2;
        }
    }

你说的是不可能的。一旦 class 拥有一个委托实例,就没有人可以阻止它调用它。因此,如果 class B 能够将委托传递给 myMethod,它也可以直接调用该委托,除非 methodAmethodB 需要特殊的参数,只有 A 知道,可以做任何有用的事情。

做类似事情的一种方法是创建一个名为 MethodOfA 的枚举,并将 MethodAMethodB 声明为枚举的可能值。在classA声明一个privateDictionary<MethodOfA, MyDelegate> methodDict,记录每个枚举值对应的是什么。然后声明另一个 myMethod 的重载,它需要一个 MethodOfA 像这样:

public static int myMethod(int data, MethodOfA action) 
    => myMethod(data, methodDict[action]);

不过,这对我来说是个糟糕的设计。也许你一开始就不需要 myMethod(int, MyDelegate) 的重载,只需检查枚举即可执行相应的操作。您可以尝试的另一件事是 strategy pattern.