Accessibility between Action and Delegate

2019-09-15 18:48发布

In the code below I created a delegate named Mhd - just like the Action delegate.
My question: if the two delegates are public, why only Action delegate is visible from another class and not 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();

any help is appreciated :)

3条回答
我欲成王,谁敢阻挡
2楼-- · 2019-09-15 19:12

Because Mhd is not a member of your class. It's a delegate type that you declared in your class.

So you can't treat it like a member method or property but you can use it to declare a variable of that type

Test.Mhd myDelegate;
查看更多
看我几分像从前
3楼-- · 2019-09-15 19:15

For my answer to make sense, it's important to remember the definition of a delegate. According to MSDN:

A delegate is a reference type that can be used to encapsulate a named or an anonymous method.

A delegate is a reference?!?!

If you are familiar with C++, you know that another way of saying reference is pointer. (In fact, C++ developers get similar functionality to C# delegates via function pointers.)

What is the significance of delegates being references? Among the basic constructs provided by the common type system, the .NET Framework has another reference type: class. Saying that a delegate is a reference type is just like saying that a delegate is a class. Let's review how we use classes.

There are 3 steps you need to follow before you can use an instance of a class:

  • Type declaration: class Test { public Action Yaser; }
  • Instance declaration: class Test testClassObject;
  • Instantiation: testClassObject = new Test();

(Typically, we combine instance declaration and instantiation).

We said that delegates are classes. Therefore, delegate use follows the same pattern:

  • Type declaration: public delegate void Mhd();
  • Instance declaration: public Mhd myMhd;
  • Instantiation: myDelegateField = new Mhd(SomeMethod);

But wait, what is SomeMethod? Truly, it doesn't matter. All that we know is that its signature must match that of Mhd. In other words, void SomeMethod()

Let's inspect and fix your class declaration. A possible implementation is shown below:

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
    }
}
查看更多
冷血范
4楼-- · 2019-09-15 19:19
    public Action Yaser;

declares a field of type Action, whereas

    public delegate void Mhd();

declares the Mhd as delegate type.

查看更多
登录 后发表回答