私は現在、いくつかの古いC#コードを使用しています。これは、基本的に、次のような「プロパティ」としてTypeを使用することのみを目的として派生型を使用します。
public abstract class Fruit
{
public int Property { get; set; }
}
public class Apple : Fruit {}
public class Pear : Fruit {}
その後:
public void Foo(Fruit item)
{
if(item is Apple)
{
// do something
return;
}
if(item is Pear)
{
// do something
return;
}
throw new ArgumentOutOfRangeException("item");
}
'type'を指定するためにBaseClassにenumプロパティを含めたでしょう:
public class Fruit
{
public int Property { get; set; }
public FruitType Type { get; set; }
}
public enum FruitType
{
Apple,
Pear
}
そしてそれをこうして使用しました:
public void Foo(Fruit item)
{
switch(item.Type)
{
case FruitType.Apple:
// do something
break;
case FruitType.Pear:
// do something
break;
default:
throw new ArgumentOutOfRangeException();
}
}
前者のパターンは継承の誤用だと思いますが、このコードを書き直す前に考慮すべき利点はありますか?