更改传入虚拟方法的类型

时间:2012-01-14 04:39:33

标签: c# polymorphism override virtual

我有一个关于在虚拟方法中更改参数类型的问题。首先,我将解释这个场景。

这是可以执行命令的用户的基本界面

public interface IUserThatExecutesCommands
{
   bool IsInRole(string role);
} 

这是该基本界面的扩展,需要用户拥有Eminence概念

public interface IUserThatExecutesEminenceCommands : IUserThatExecutesCommands
{
   int Eminence { get; }
}

现在,这是定义IUserThatExecutesCommands使用

命令的基本抽象UserCommand类
public abstract class UserCommand
{
   public virtual bool CanBeExecutedBy(IUserThatExecutesCommands user)
   {
       // For the purpose of simplification I have not included the actual implementation of this method.
       return UserIsInOneOfAllowedRoles(user);
   }
}

以下是该类的扩展,它引入了Eminence的概念,因此需要使用IUserThatExecutesEminenceCommands。目前这会导致编译器错误,因为我已经更改了传入的使用类型。

public abstract class EminenceCommand : UserCommand
{
        public override bool CanBeExecutedBy(IUserThatExecutesEminenceCommands user)
        {
            return user.Eminence >= _requiredEminence;
        }
}

我的问题是,有没有办法可以覆盖CanBeExecutedBy函数,以便我可以更改传入的用户类型?我希望能够扩展UserCommand类,但目前我无法解决这个问题。

由于

2 个答案:

答案 0 :(得分:0)

试试这个:

public abstract class EminenceCommand : UserCommand 
{ 
        public override bool CanBeExecutedBy(IUserThatExecutesCommands user) 
        { 
            // Dynamically check the type of user passed in and only check priveleges if correct type
            IUserThatExecutesEminenceCommands u = user as IUserThatExecutesEminenceCommands;
            if( u == null) {
                 return false;
            }
            return u.Eminence >= _requiredEminence; 
        } 
} 

答案 1 :(得分:0)

为虚拟功能建立签名后,它就成为您无法更改的合同。但是,您可以将user参数测试为CanBeExecutedBy,并查看它是否支持任何所需的接口。所以,你的方法看起来像这样:

public override bool CanBeExecutedBy(IUserThatExecutesCommands user)
{
    IUserThatExecutesEminenceCommands u = user as IUserThatExecutesEminenceCommands;
    if (u == null)
    {
        // TODO: Ignore the arg, throw an exception or do something else.
        return false;
    }

    return u.Eminence >= _requiredEminence;
}