我有以下示例代码。最佳做法是什么?比较值或比较类型以执行某种业务逻辑:
public Customer
{
public Category {get;set;}
public CategoryName {get;set;} //e.g. "Category A" or "Category B"
}
public Category{}
public CategoryA : Category {}
public CategoryB : Category {}
public void Main()
{
Customer customer = new Customer();
// Option 1:
if(customer.CategoryName == "Category A")
{
CategoryA catA= customer.Category as CategoryA;
DoSomething(catA)
}
// Option 2:
CategoryA catA= customer.Category as CategoryA;
if(catA != null)
{
DoSomething(catA)
}
// Option 3:
if(customer.Catgeory is Category A)
{
CatgeoryA catA= customer.Category as CategoryA;
DoSomething(catA)
}
}
本守则仅作说明之用。