次のC#コードがあります。正常に動作します。しかし、メソッドはis 演算子を使用することで複数の条件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();
}
}
参考文献