9

Here is the original question where I'm looking for a way to generate a generic delegate: .Net generate generic methods

Here is the code to generate a generic delegate in .NET 3.5:

public delegate void PropertyChangedDelegate<OwnerType, PropertyType>(OwnerType sender, String propertyName, PropertyType oldValue, PropertyType newValue);

EventInfo eventInfo = type.GetEvent(property.Name + "Changed");
MethodInfo propertyChangedMethodInfo = this.GetType().GetMethod("content_PropertyChanged", BindingFlags.NonPublic | BindingFlags.Instance);
MethodInfo genericPropertyChangedMethodInfo = propertyChangedMethodInfo.MakeGenericMethod(eventInfo.EventHandlerType.GetGenericArguments());
Delegate delegate_ = Delegate.CreateDelegate(eventInfo.EventHandlerType, genericPropertyChangedMethodInfo);
eventInfo.AddEventHandler(obj, delegate_);

void content_PropertyChanged<OwnerType, PropertyType>(OwnerType sender, String propertyName, PropertyType oldValue, PropertyType newValue)
{
}

This works in .NET 3.5, but now when I tried to port to the compact framework 3.5, the Delegate.CreateDelegate method requires a third parameter... The parameter description says:

it should be the first argument, or 'the object to which the delegate is bound'.

I tried putting 'obj' in there, and 'this', and null, and I always get an invalid argument exception.

Any ideas?

Community
  • 1
  • 1
Ryan Brown
  • 1,017
  • 1
  • 13
  • 34
  • Could it be that there is something wrong with the other two arguments on the compact platform? – Lasse V. Karlsen May 17 '13 at 17:50
  • I tried the exact same thing with three arguments like this on the desktop .NET and it worked: Delegate delegate_ = Delegate.CreateDelegate(eventInfo.EventHandlerType, this, genericPropertyChangedMethodInfo); – Ryan Brown May 17 '13 at 19:40
  • I looked closer and the error said: "ReturnType for Open Generic methods is not supported"... hmmm – Ryan Brown May 17 '13 at 19:42
  • I think this question is related: http://stackoverflow.com/questions/18148849/why-cant-i-call-delegate-createdelegate-in-my-portable-class-library – HerbalMart Mar 04 '14 at 10:10

2 Answers2

1

Unfortunately .NETCF (.NET Compact Framework) doesn't support the same method signatures as .NET (full framework) as only a subset is implemented.

You can see this on the MSDN library where only one of the ten method overloads is "Supported by the .NET Compact Framework", indicated with the small graphic of a PDA/mobile.

CreateDelegate method

This means you have to use Delegate.CreateDelegate(Type, Object, MethodInfo) in .NETCF.

Kevin Hogg
  • 1,771
  • 25
  • 34
0

Please check the example section in the link below and see if it helps.

http://msdn.microsoft.com/en-us/library/74x8f551.aspx

Regards,

Zahir Khan

Zahir Khan
  • 35
  • 2
  • 7