覆盖静态方法 [英] Override a static method

查看:139
本文介绍了覆盖静态方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我从RolesService继承延伸出的新类。在RolesService我有一个静态methog,我想在我的新派生类重写。当我拨打电话从我的派生类对象不使用它实际上调用基类方法重写的静态方法。有任何想法吗?

 公共类RolesService:IRolesService
    {
    公共静态布尔的isUserInRole(用户名字符串,字符串角色名)
    {
        返回Roles.IsUserInRole(用户名,角色名);
    }
}公共类MockRoleService:RolesService
{
    市民新的静态布尔的isUserInRole(用户名字符串,字符串角色名)
    {
        返回true;
    }
}


解决方案

执行以下操作将允许您解决的静态调用。要使用时,你需要MockRolesService可以传递在code需要通过依赖注入的IRolesService呢。

 公共接口IRolesService
{
    布尔的isUserInRole(用户名字符串,字符串角色名);
}公共类RolesService:IRolesService
{
    公共BOOL的isUserInRole(用户名字符串,字符串角色名)
    {
        返回Roles.IsUserInRole(用户名,角色名);
    }
}公共类MockRoleService:IRolesService
{
    公共BOOL的isUserInRole(用户名字符串,字符串角色名)
    {
        返回true;
    }
}

I am extending a new class by inheriting from RolesService. In RolesService I have a static methog that I would like to override in my newly derived class. When I make the call from my derived object it does not use the overridden static method it actually calls the base class method. Any ideas?

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;
    }
}

解决方案

Doing the following the will allow you to work around the static call. Where you want to use the code take an IRolesService via dependency injection then when you need MockRolesService you can pass that in.

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;
    }
}

这篇关于覆盖静态方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆