将委托作为属性传递
Passing a delegate as an Attribute
我正在尝试使用 this 方法将委托作为参数传递。
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;
}
);
}
}
当我尝试使用反射创建委托时出现错误
spaceGetter = (SpaceIdGetter)Delegate.CreateDelegate(delegateType, delegateType.GetMethod(delegateName));
Type must derive from Delegate.
编辑:这是我的使用方式
[SpaceId(typeof(ContextInfo), "GetSpaceId")]
public virtual string Body { get; set; }
ContextInfo 不是委托,Delegate.CreateDelegate 必须接受委托。尝试:
spaceGetter = (SpaceIdGetter)Delegate.CreateDelegate(typeof(Action<Guid>), delegateType.GetMethod(delegateName));
ContextInfo
实际上是一个已经创建委托类型的工厂 - 所以不需要通过反射创建委托 - 你只需要通过反射调用工厂:
public SpaceIdAttribute(Type delegateType, string delegateName)
{
var factoryMethod = delegateType.GetMethod(delegateName);
spaceGetter = (SpaceIdGetter)factoryMethod.Invoke(null, null);
}
我正在尝试使用 this 方法将委托作为参数传递。
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;
}
);
}
}
当我尝试使用反射创建委托时出现错误
spaceGetter = (SpaceIdGetter)Delegate.CreateDelegate(delegateType, delegateType.GetMethod(delegateName));
Type must derive from Delegate.
编辑:这是我的使用方式
[SpaceId(typeof(ContextInfo), "GetSpaceId")]
public virtual string Body { get; set; }
ContextInfo 不是委托,Delegate.CreateDelegate 必须接受委托。尝试:
spaceGetter = (SpaceIdGetter)Delegate.CreateDelegate(typeof(Action<Guid>), delegateType.GetMethod(delegateName));
ContextInfo
实际上是一个已经创建委托类型的工厂 - 所以不需要通过反射创建委托 - 你只需要通过反射调用工厂:
public SpaceIdAttribute(Type delegateType, string delegateName)
{
var factoryMethod = delegateType.GetMethod(delegateName);
spaceGetter = (SpaceIdGetter)factoryMethod.Invoke(null, null);
}