我有以下 C# 代码。效果很好;但是GetDestination()
方法杂乱地包含多个if
条件通过使用是运算符.
在 .Net 4.0(或更高版本)中,避免这些“if”条件的最佳方法是什么?
编辑:角色是业务模型的一部分,目的地纯粹是使用该业务模型的一个特定应用程序的工件。
CODE
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 具有不同类型的委托:更清晰的非字符串方法名称?
- Jon Skeet:让反思飞翔并探索代表
- if-else 与 switch 与委托字典
- 带委托或开关的字典?
- C# 中的表达式和委托
Having 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
当它没有在派生类中被重写时的值。
Usage:
string destination = (new Accountant()).Destination;
Console.WriteLine(destination);
Console.ReadLine();
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)