【发布时间】:2014-01-21 14:54:55
【问题描述】:
我有以下 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();
}
}
参考文献
【问题讨论】:
-
您可以将其替换为
string.Format(@"\{0}Home", x.GetType().Name)。如果这是一个好主意是另一个取决于您的设计的问题。 -
为什么不让 GetDestination() 成为 Role 的方法并覆盖它?
-
您展示的任何类是否有可能被进一步子类化?
-
@Rik 不同意。这显然只是一个代码示例,目的是询问 OOP 技术。
-
@Lijo:好吧,如果你有一个
Type到string的字典,你需要知道对象的类型会有一个完全匹配的......见在可能有子类化的情况下,我对替代方案的回答。
标签: c# oop design-patterns double-dispatch multimethod