0

I'm trying to use this method to pass a delegate as a parameter.

public delegate Guid SpaceIdGetter();
public class SpaceIdAttribute : Attribute
    {
        public SpaceIdGetter spaceGetter { get; set; }

        public SpaceIdAttribute(Type delegateType, string delegateName)
        {
            spaceGetter = (SpaceIdGetter)Delegate.CreateDelegate(delegateType, delegateType.GetMethod(delegateName));
        }
    }

    public static class ContextInfo
    {
        public static SpaceIdGetter GetSpaceId()
        {
            return new SpaceIdGetter( () =>
                    {
                        return Guid.Empty;
                    }
                );
        }
    }

I'm getting an error when I try to create the delegate with reflection

spaceGetter = (SpaceIdGetter)Delegate.CreateDelegate(delegateType, delegateType.GetMethod(delegateName));

Type must derive from Delegate.

Edit: here's how I'm using it

[SpaceId(typeof(ContextInfo), "GetSpaceId")]
public virtual string Body { get; set; }
Community
  • 1
  • 1
Adrian Buzea
  • 826
  • 2
  • 11
  • 33

2 Answers2

2

The ContextInfo is actually a factory already creating the delegate type - so no need to create delegate via reflection - you just have to call the factory via reflection:

public SpaceIdAttribute(Type delegateType, string delegateName)
{
  var factoryMethod = delegateType.GetMethod(delegateName);
  spaceGetter = (SpaceIdGetter)factoryMethod.Invoke(null, null);
}
Ondrej Svejdar
  • 21,349
  • 5
  • 54
  • 89
0

ContextInfo is not a Delegate and Delegate.CreateDelegate must take a delegate. Try: spaceGetter = (SpaceIdGetter)Delegate.CreateDelegate(typeof(Action<Guid>), delegateType.GetMethod(delegateName));

Arnon Axelrod
  • 1,444
  • 2
  • 13
  • 21
  • Getting this now: Cannot bind to the target method because its signature or security transparency is not compatible with that of the delegate type. – Adrian Buzea Aug 06 '15 at 08:52