I use a serializer "NetStack.BitBuffer". With reflection I get all read methods like Int32 ReadInt, UInt32 ReadUInt etc.
To speed up the invoke from the methodinfo I create delegates but suddently after next time I wanted to work and even was recording it to make vlog but same code shows exception. I debugged it and all values are correct but still it is not working.
public class BitBuffer // Recreated to test it
{
public int ReadInt()
{
return 1;
}
}
[Test]
public void DelegateCreateTest()
{
BitBuffer bitBuffer = new BitBuffer();
MethodInfo readIntMethod = bitBuffer.GetType().GetMethod("ReadInt");
Assert.IsNotNull(readIntMethod, "Should not be null");
var func = (Func<object>)Delegate.CreateDelegate(typeof(Func<object>), bitBuffer, readIntMethod);
Assert.IsNotNull(func, "Should not be null");
}
The test code above worked before the exception started to show.
System.ArgumentException: 'Cannot bind to the target method because its signature is not compatible with that of the delegate type.'
If change my self to Func<int>
then it works but you could guess it.. all other methods with other return type will not work.
If I google it actually shouldn't even possible to do this except post: The identical code which I found was here and seems like it should actually work: https://stackoverflow.com/a/44595323/5103256
I really get crazy like error in the matrix and cannot explain why suddently it is not working. Tooooo bad I didn't use git to follow what is different.
CodePudding user response:
The documentation says:
the return type of a delegate is compatible with the return type of a method if the return type of the method is more restrictive than the return type of the delegate.
While all reference types are considered compatible to object
, value types like int
would require boxing to produce a compatible type. CreateDelegate
does not offer this service.