简体   繁体   中英

How to pass a delegate to another class

In my main class 'A' I have declared a function and delegate to call that function, I want to pass my delegate to another class 'B' but how will class B know what type the delegate is?

class A

public delegate void SendInfo(string[] info);
SendInfo sendInfo = new SendInfo(SendInformation); //I have a function SendInformation

B b = new B();
b.SetDelegate(sendInfo);

class B

public delegate void SendInfo(string[] info); //I know this is wrong but how will 
SendInfo SendInformation;                     //this class know what SendInfo is?

public void SetDelegate(SendInfo sendinfo)    //What type is this parameter?
{
    sendinfo.GetType();
    SendInformation = sendinfo;
}

Thanks,

Eamonn

When you declare the delegate 'in' class A, you declare it as a sub-type of class A. So it's of type ClassA.SendInfo for example. In class B you could use

public void SetDelegate(ClassA.SendInfo sendinfo)

Alternatively, declare the delegate outside of the code for class A - then it will simply be another type you can reference by name ( SendInfo ).

Why are you declaring two separate delegate types with the same signature? Declare a single delegate type (if you really have to - use the Func and Action families where possible) outside any other classes, and use that everywhere.

You need to be aware that when you write:

public delegate void SendInfo(string[] info);

that really is declaring a type - and you can declare that type directly in a namespace; it doesn't have to be the member of another type.

只需在代理命名空间内直接声明委托不是在类中。

You can do this with using static .

class A contains delegate declaration.

public delegate void SendInfo(string[] info);

class B contains delegate type usage.

using static ClassA.SendInfo;

public void SetDelegate(SendInfo sendinfo)
{
    ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM