相关疑难解决方法(0)

在C#4.0中使用动态的RuntimeBinderException

我有一个界面:

public abstract class Authorizer<T> where T : RequiresAuthorization
{
    public AuthorizationStatus Authorize(T record)
    {
        // Perform authorization specific stuff
        // and then hand off to an abstract method to handle T-specific stuff
        // that should happen when authorization is successful

    }
}
Run Code Online (Sandbox Code Playgroud)

然后,我有一堆不同的类,它们都实现了RequiresAuthorization,相应地,Authorizer<T>每个类都有一个(我的域中的每个业务对象在授权记录后都需要不同的逻辑来执行).

我也使用UnityContainer,我注册了各种各样Authorizer<T>的.然后我有一些代码如下,从数据库中找到正确的记录并授权它:

void Authorize(RequiresAuthorization item)
{
    var dbItem = ChildContainer.Resolve<IAuthorizationRepository>()
                               .RetrieveRequiresAuthorizationById(item.Id);
    var authorizerType = type.GetType(String.Format("Foo.Authorizer`1[[{0}]], Foo",
                             dbItem.GetType().AssemblyQualifiedName));
    dynamic authorizer = ChildContainer.Resolve(type) as dynamic;

    authorizer.Authorize(dbItem);
}
Run Code Online (Sandbox Code Playgroud)

基本上,我正在使用对象上的Id从数据库中检索它.在后台,NHibernate负责确定它是什么类型的RequiresAuthorization.然后我想为它找到合适的Authorizer(我不知道在编译时Authorizer<T>我需要什么实现,所以我有一点反思来获得完全限定类型).为了实现这一点,我使用UnityContainer的Resolve方法的非泛型重载来从配置中查找正确的授权器.

最后,我想在授权器上调用Authorize,传递我从NHibernate回来的对象.

现在,针对这个问题:

在VS2010的Beta2中,上面的代码完美无缺.在RC和RTM上,一旦我进行了Authorize()调用,我就得到一个RuntimeBinderException,说"最好的重载方法匹配 …

c# reflection exception dynamic

6
推荐指数
1
解决办法
4971
查看次数

标签 统计

c# ×1

dynamic ×1

exception ×1

reflection ×1