C
Join ServerC#
help
How do delegates work
MMemw9/23/2022
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
MMemw9/23/2022
also the delegate must be async since it's a Discord.Net event
MMemw9/23/2022
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
MMemw9/23/2022
i mean in this case it should be some type related to any method, so i don't actually know how to do this.
KKouhai9/23/2022
You need to declare a delegate that matches your methods' signature
KKouhai9/23/2022
method.CreateDelegate<YourDelegate>()
WWindows10CE9/23/2022
what is the event you're trying to add to?
MMemw9/23/2022
the event is whatever it gets from the string passed in the attribute constructor arg
WWindows10CE9/23/2022
well i'll give an example
MMemw9/23/2022
this is what i don't understand basically
WWindows10CE9/23/2022
if you had
public event Func<int, Task> SomeEvent;
typeof(Func<int, Task>)
is what you pass to CreateDelegateMMemw9/23/2022
i see, so that's the function return type then
WWindows10CE9/23/2022
its not its return type, thats how you define events
WWindows10CE9/23/2022
Func<T1, TRet>
is a delegate typeWWindows10CE9/23/2022
it seems like you have an eventinfo there
WWindows10CE9/23/2022
which means you can get that type using https://learn.microsoft.com/en-us/dotnet/api/system.reflection.eventinfo.eventhandlertype?view=net-6.0#system-reflection-eventinfo-eventhandlertype
MMemw9/23/2022
so EventInfo.GetType?
WWindows10CE9/23/2022
no
WWindows10CE9/23/2022
EventInfo.EventHandlerType
WWindows10CE9/23/2022
you're getting the EventInfo from
GetType().GetEvent(...)
MMemw9/23/2022
ok, i'l try to pass (use) that
MMemw9/23/2022
i'l split stuff in variables and pass (use) that, thanks
MMemw9/23/2022
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?
hat of the delegate type.
this means that the function the event expects is not compatible as far as i know?
MMemw9/23/2022
@Windows10CE
MMemw9/23/2022
ah it works, it just had to be static, my bad, thanks a lot