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
C# using delegates var md = new MyDelegate(MyCallback); md(); void MyCallback() { Console. WriteLine("Calling callback"); } delegate void MyDelegate(); We declare a delegate, create an instance of the delegate and invoke it. var md = new MyDelegate(MyCallback);
Because the instantiated delegate is an object, it can be passed as an argument, or assigned to a property. This allows a method to accept a delegate as a parameter, and call the delegate at some later time.
You can pass methods as parameters to a delegate to allow the delegate to point to the method. Delegates are used to define callback methods and implement event handling, and they are declared using the “delegate” keyword. You can declare a delegate that can appear on its own or even nested inside a class.
Key Steps to DelegationCreate a delegate protocol that defines the messages sent to the delegate. Create a delegate property in the delegating class to keep track of the delegate. Adopt and implement the delegate protocol in the delegate class. Call the delegate from the delegating object.
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With