Gab*_*abe 39 c# asp.net asp.net-mvc
我通过继承RolesService来扩展一个新类.在RolesService中,我有一个静态方法,我想在我新派生的类中覆盖它.当我从派生对象进行调用时,它不使用重写的静态方法,它实际上调用基类方法.有任何想法吗?
public class RolesService : IRolesService
{
public static bool IsUserInRole(string username, string rolename)
{
return Roles.IsUserInRole(username, rolename);
}
}
public class MockRoleService : RolesService
{
public new static bool IsUserInRole(string username, string rolename)
{
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
MHi*_*ton 19
执行以下操作将允许您解决静态调用.你想要使用代码的地方通过依赖注入获取IRolesService,然后当你需要MockRolesService时,你可以传入它.
public interface IRolesService
{
bool IsUserInRole(string username, string rolename);
}
public class RolesService : IRolesService
{
public bool IsUserInRole(string username, string rolename)
{
return Roles.IsUserInRole(username, rolename);
}
}
public class MockRoleService : IRolesService
{
public bool IsUserInRole(string username, string rolename)
{
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
Aar*_*ght 17
您不能覆盖静态方法.
如果你考虑一下,它就没有意义; 为了进行虚拟调度,您需要一个要检查的对象的实际实例.
静态方法也无法实现接口; 如果这个类正在实现一个IRolesService接口,那么我认为该方法根本不应该是静态的.拥有实例方法的设计更好,因此您可以MockRoleService在准备好时将实际服务替换掉.
| 归档时间: |
|
| 查看次数: |
61736 次 |
| 最近记录: |