gpt4 book ai didi

c# - 通用方法和无效上下文异常

转载 作者:行者123 更新时间:2023-12-02 05:00:59 25 4
gpt4 key购买 nike

我正在尝试编写自定义授权服务,我在其中注册了一个模块来检查代表可用事件的特定枚举的权限:

public interface IAuthorizationService
{
void Register<T>(IAuthorizationModule module);
bool Authorize<T>(T activity);
}

public class AuthorizationService : IAuthorizationService
{
private readonly Dictionary<Type, IAuthorizationModule> activities;

public AuthorizationService()
{
activities = new Dictionary<Type, IAuthorizationModule>();
}

public void Register<T>(IAuthorizationModule module)
{
activities[typeof(T)] = module;
}

public bool Authorize<T>(T activity)
{
return activities[typeof(T)].Authorize(activity);
}
}
public interface IAuthorizationModule
{
bool Authorize<T>(T activity);
}

public class OrderAuthModule : IAuthorizationModule
{
public bool Authorize<OrderActivity>(OrderActivity activity)
{
return activity == OrderActivity.Cancel;
}
}

public enum OrderActivity
{
Place,
Cancel,
Refund
}

此代码编译失败,出现以下异常:

'OrderActivity' is a 'type parameter', which is not valid in the given context

在线:return activity == OrderActivity.Cancel; .

我无法将接口(interface)声明为 IAuthorizationModule<T>因为我需要 <Type, IAuthorizationModule> 的字典注册将响应类型 T 的模块(枚举)。

我在这里缺少什么?

最佳答案

好吧,你的设计不符合我的口味。根据您的具体类和 AuthorizeService 的实现,我假设每个 IAuthorizationModule 应该只负责一种类型的事件。如果我是对的,那么接口(interface)应该声明为

public interface IAuthorizationModule<T>
{
bool Authorize(T activity);
}

public class OrderAuthModule : IAuthorizationModule<OrderActivity>
{
public bool Authorize<OrderActivity>(OrderActivity activity)
{
return activity == OrderActivity.Cancel;
}
}

您还需要相应地修改AuthorizationService:

public class AuthorizationService : IAuthorizationService
{
private readonly Dictionary<Type, object> activities;

public AuthorizationService()
{
activities = new Dictionary<Type, object>();
}

public void Register<T>(IAuthorizationModule<T> module)
{
activities[typeof(T)] = module;
}

public bool Authorize<T>(T activity)
{
return ((IAuthorizationModule<T>)activities[typeof(T)]).Authorize(activity);
}
}

这样可以更轻松地实现每个 IAuthorizationModule

关于c# - 通用方法和无效上下文异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17099035/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com