Action和Delegate之间的可访问性

本文关键字:访问 之间 Delegate Action | 更新日期: 2023-09-27 18:25:13

在下面的代码中,我创建了一个名为Mhd的委托,就像Action委托一样
我的问题:如果这两个委托是公共,为什么从另一个类只能看到Action委托而不能看到Mhd

static void Main(string[] args)
    {
        new Test().Yaser(); //this can be done
        new Test().mhd(); //this can not be done
    }
    class Test
    {
        public Action Yaser;
        public delegate void Mhd();
    }
    //and Action definition is   public delegate void Action();

如有任何帮助,我们将不胜感激:)

Action和Delegate之间的可访问性

为了让我的答案有意义,记住委托的定义很重要。根据MSDN:

委托是一种引用类型,可用于封装命名或匿名方法。

委托是引用?!?!

如果你熟悉C++,你就会知道reference的另一种说法是pointer。(事实上,C++开发人员通过函数指针获得与C#委托类似的功能。)

代表作为参考人的意义是什么?在通用类型系统提供的基本构造中,.NET Framework有另一个引用类型:class。说委托是引用类型就像说委托是类一样。让我们回顾一下如何使用类。

在使用类的实例之前,需要遵循以下3个步骤:

  • 类型声明:class Test { public Action Yaser; }
  • 实例声明:class Test testClassObject;
  • 实例化:testClassObject = new Test();

(通常,我们将实例声明和实例化结合起来)。

我们说过,代表就是阶级。因此,委托使用遵循相同的模式:

  • 类型声明:public delegate void Mhd();
  • 实例声明:public Mhd myMhd;
  • 实例化:myDelegateField = new Mhd(SomeMethod);

等等,什么是SomeMethod?的确,这并不重要。我们所知道的是,它的签名必须与Mhd的签名相匹配。换句话说,void SomeMethod()

让我们检查并修复您的类声明。一种可能的实现方式如下所示:

class Test
{
    public Action Yaser;        // instance declaration
    public delegate void Mhd(); // type declaration
    public Mhd myMhd;           // instance declaration
    public Test()
    {
        // instantiation
        this.myMhd = new Mhd(this.SomeMethod);
    }
    private void SomeMethod()
    {
        // your implementation
    }
}
    public Action Yaser;

声明类型为Action的字段,而

    public delegate void Mhd();

Mhd声明为委托类型。

因为Mhd不是您的类的成员。它是您在类中声明的委托类型。

因此,您不能将其视为成员方法或属性,但可以使用它来声明类型的变量

Test.Mhd myDelegate;