C
C#2y ago
memw

How do delegates work

I have a little problem understanding what type i need to pass a delegate to AddEventHandler because i'm getting the function from reflection and MethodInfo.CreateDelegate tells me i need to pass a type which i don't understand what would that type be for or what derives from a delegate exactly
13 Replies
memw
memw2y ago
also the delegate must be async since it's a Discord.Net event
foreach (MethodInfo method in cConfig.EventsAssembly.GetTypes().SelectMany(t => t.GetMethods()).Where(m => m.GetCustomAttributes(typeof(EventAttribute), false).Length > 0).ToArray())
{
CustomAttributeData catData = method.GetCustomAttributesData().First(a => a.AttributeType.Name == "EventAttribute");
GetType().GetEvent((string)catData.ConstructorArguments.First().Value!)!.AddEventHandler(this, method.CreateDelegate(typeof(void)));
}
foreach (MethodInfo method in cConfig.EventsAssembly.GetTypes().SelectMany(t => t.GetMethods()).Where(m => m.GetCustomAttributes(typeof(EventAttribute), false).Length > 0).ToArray())
{
CustomAttributeData catData = method.GetCustomAttributesData().First(a => a.AttributeType.Name == "EventAttribute");
GetType().GetEvent((string)catData.ConstructorArguments.First().Value!)!.AddEventHandler(this, method.CreateDelegate(typeof(void)));
}
That typeof(void) in there i just put because at this point i tried everything lol, i don't know what type to put in there i mean in this case it should be some type related to any method, so i don't actually know how to do this.
Kouhai
Kouhai2y ago
You need to declare a delegate that matches your methods' signature method.CreateDelegate<YourDelegate>()
Aaron
Aaron2y ago
what is the event you're trying to add to?
memw
memw2y ago
the event is whatever it gets from the string passed in the attribute constructor arg
Aaron
Aaron2y ago
well i'll give an example
memw
memw2y ago
this is what i don't understand basically
Aaron
Aaron2y ago
if you had
public event Func<int, Task> SomeEvent;
public event Func<int, Task> SomeEvent;
typeof(Func<int, Task>) is what you pass to CreateDelegate
memw
memw2y ago
i see, so that's the function return type then
Aaron
Aaron2y ago
its not its return type, thats how you define events Func<T1, TRet> is a delegate type it seems like you have an eventinfo there
Aaron
Aaron2y ago
memw
memw2y ago
so EventInfo.GetType?
Aaron
Aaron2y ago
no EventInfo.EventHandlerType you're getting the EventInfo from GetType().GetEvent(...)
memw
memw2y ago
ok, i'l try to pass (use) that i'l split stuff in variables and pass (use) that, thanks Cannot bind to the target method because its signature is not compatible with t hat of the delegate type. this means that the function the event expects is not compatible as far as i know? @Windows10CE ah it works, it just had to be static, my bad, thanks a lot
Want results from more Discord servers?
Add your server
More Posts