【发布时间】:2014-05-20 23:42:57
【问题描述】:
潜伏多年后第一次在这里发帖,在此先感谢您的帮助。
我试图在静态类中的控制器实例上创建委托,但出现错误: “无法绑定到目标方法,因为它的签名或安全透明度与委托类型的不兼容。”
错误发生在GetReasonsForDeny方法中,这里我传入了entity和typeof(HomeController)。
我的代码在这里:
public class HomeController : Project.Web.Controllers.Base.Controller
{
//Properties
IUserRepository UserRepository { get; set; }
//Constructor
HomeController(IUserRepository userRepository)
: Project.Web.Controllers.Base.Controller
{
UserRepository = userRepository;
}
public List<string> CanPerformAction(IEntity entity)
{
List<string> reasonsForDeny = new List<string>();
TestEntity domainEntity = entity as TestEntity;
if (domainEntity != null)
VerifyRules(domainEntity, UserRepository, out reasonsForDeny);
return reasonsForDeny;
}
}
public static class ControllerActionHelper
{
private static List<string> GetReasonsForDeny(IEntity entity, Type Controller)
{
List<string> reasonsForDeny = new List<string>();
MethodInfo accessMethod = controller.GetMethod("CanPerformAction");
if (accessMethod != null)
{
/***** Error Here ********/
Func<IEntity, List<string>> accessDelegate = (Func<IEntity, List<string>>)Delegate.CreateDelegate(typeof(Func<IEntity, List<string>>), controller, accessMethod);
reasonsForDeny = accessDelegate(entity);
}
return reasonsForDeny
}
}
我还尝试通过将 null 传递给 CreateDelegate 将代理更改为静态,如下所示,但是如果我这样做,那么当调用 CanPerformAction 时,我的 UserRepository 的值为 null。
// Before
Func<IEntity, List<string>> accessDelegate = (Func<IEntity, List<string>>)Delegate.CreateDelegate(typeof(Func<IEntity, List<string>>), controller, accessMethod);
// After
Func<IEntity, List<string>> accessDelegate = (Func<IEntity, List<string>>)Delegate.CreateDelegate(typeof(Func<IEntity, List<string>>), null, accessMethod);
最后,我尝试创建一个非静态类来创建委托,然后将其返回给静态类,如下所示,但非静态类得到相同的错误:“无法绑定到目标方法因为它的签名或安全透明性与委托类型的不兼容。”
public static class ControllerActionHelper
{
private static List<string> GetReasonsForDeny(IEntity entity, Type Controller)
{
List<string> reasonsForDeny = new List<string>();
MethodInfo accessMethod = controller.GetMethod("CanPerformAction");
if (accessMethod != null)
{
var tempInstance = new foo();
Func<IEntity, List<string>> accessDelegate = foo.MakeMyDelegatePlease(controller, accessMethod, entity);
reasonsForDeny = accessDelegate(entity);
}
return reasonsForDeny
}
}
public class foo
{
public Func<IEntity, List<string>> MakeMyDelegatePlease(Type controller, MethodInfo accessMethod, IEntity entity)
{
/********* Error Here ************/
Func<IEntity, List<string>> accessDelegate = (Func<IEntity, List<string>>)Delegate.CreateDelegate(typeof(Func<IEntity, List<string>>), controller, accessMethod);
return accessDelegate;
}
}
任何建议将不胜感激!
【问题讨论】:
-
第一个问题写得很好。我们需要更多好的 ASP.Net MVC 问题;这些模式对许多人来说是新的,平台正在迅速成熟。
标签: c# asp.net-mvc