c# - .Net 4.0 重构现有 "if"条件和 "is"运算符的优化代码

标签 c# oop design-patterns double-dispatch multimethod

我有以下 C# 代码。它工作正常;但是 GetDestination() 方法通过使用 is operator 被多个 if 条件弄得乱七八糟。 .

在 .Net 4.0(或更高版本)中,避免这些“if”条件的最佳方法是什么?

编辑:角色是业务模型的一部分,目的地纯粹是使用该业务模型的特定应用程序的产物。

代码

public class Role { }
public class Manager : Role { }
public class Accountant : Role { }
public class Attender : Role { }
public class Cleaner : Role { }
public class Security : Role { }

class Program
{
    static string GetDestination(Role x)
    {
        string destination = @"\Home";

        if (x is Manager)
        {
            destination = @"\ManagerHomeA";
        }

        if (x is Accountant)
        {
            destination = @"\AccountantHomeC";
        }

        if (x is Cleaner)
        {
            destination = @"\Cleaner";
        }

        return destination;

    }

    static void Main(string[] args)
    {
        string destination = GetDestination(new Accountant());
        Console.WriteLine(destination);
        Console.ReadLine();
    }
}

引用文献

  1. Dictionary<T,Delegate> with Delegates of different types: Cleaner, non string method names?
  2. Jon Skeet: Making reflection fly and exploring delegates
  3. if-else vs. switch vs. Dictionary of delegates
  4. Dictionary with delegate or switch?
  5. Expression and delegate in c#

最佳答案

具有在派生类中将被覆盖的virtual 属性应该可以解决问题:

class Role
{
    public virtual string Destination { get { return "Home"; } }
}
class Manager : Role
{
    public override string Destination { get { return "ManagerHome;"; } }
}
class Accountant : Role
{
    public override string Destination { get { return "AccountantHome;"; } }
}
class Attender : Role
{
    public override string Destination { get { return "AttenderHome;"; } }
}
class Cleaner : Role
{
    public override string Destination { get { return "CleanerHome;"; } }
}
class Security : Role { }

我没有将属性抽象化,以便在未在派生类中覆盖时提供默认的 Home 值。

用法:

string destination = (new Accountant()).Destination;
Console.WriteLine(destination);
Console.ReadLine();

关于c# - .Net 4.0 重构现有 "if"条件和 "is"运算符的优化代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21261519/

相关文章:

c# - 找不到合适的方法来覆盖 OnModelCreating()

C# 查看特定 .NET 类的源代码

swift - 需要一些一般类(class)的建议

design-patterns - 找一本关于学习 RUP 的实用方法的书

c# - ASP.NET Web API 中甚至需要 MVC 中的 M 和 V 吗?

c# - 如何从 C# 中的存储过程中获取选定的值?

c# - Xamarin Android 警报管理器问题

c++ - 是否可以创建一个容器,其对象只占用 2 位?

javascript - 对 Javascript 对象属性/字段感到困惑

oop - 名为 `User` 的类应该是单例模式的实现吗?