编程语言
首页 > 编程语言> > c# – .Net 4.0优化代码,用于重构现有的“if”条件和“is”运算符

c# – .Net 4.0优化代码,用于重构现有的“if”条件和“is”运算符

作者:互联网

我有以下C#代码.它工作正常;但是使用is operator,GetDestination()方法会被多个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();
    }
}

参考

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

解决方法:

拥有将在派生类中重写的虚拟属性应该可以解决问题:

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,oop,design-patterns,double-dispatch,multimethod
来源: https://codeday.me/bug/20190712/1441761.html