加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 19:38:51 所属栏目:百科 来源:网络整理
导读:我有以下C#代码.它工作正常;但是使用 is operator,GetDestination()方法会被多个if条件混乱. 在.Net 4.0(或更高版本)中,避免这些“if”条件的最佳方法是什么? 编辑:角色是业务模型的一部分,目标纯粹是使用该业务模型的一个特定应用程序的工件. 码 public c
我有以下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();

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读