わかりましたので、おおよそ次のようなコードを探しています。
void DoSomething(object o)
{
if (o is Sometype1) {
//cast o to Sometype and do something to it
}
else if (o is Sometype2) {
//cast o to Sometype2 and do something to it
}
...
else if (o is SometypeN) {
//cast o to SometypeN and do something to it
}
}
ここで、1 つのアプローチはo
、パラメーターとして使用されるすべてのオブジェクトに、次のようなインターフェイスを実装させることです。
interface ICanHaveSomethingDoneToMe
{
//expose various properties that the DoSomething method wants to access
}
しかし、これの問題は、すべてのオブジェクトにこのインターフェイスを実装させたくないということです。何かを行うメソッドのロジックは、実際にはオブジェクトに属していません。これに対処するには、どのパターンを使用する必要がありますか?
の一連の実装のようなものを疑っています
interface IPropertiesForDoingSomethingTo<T>
{
//expose various properties that the DoSomething method wants to access
}
良いかもしれません。実装したいオブジェクトの種類ごとに実装する必要がありますが、この新しい問題が発生します。私は時点で次のような方法が必要です
IPropertiesForDoingSomethingTo<T> GetPropsGeneric(T t);
しかし、これには大規模なスイッチが必要ですか? 次のようなメソッドがたくさんあるクラスを定義する必要がありますか
IPropertiesForDoingSomethingTo<Someobject1> GetProps(Someobject1 t);
...
IPropertiesForDoingSomethingTo<Someobject1> GetProps(SomeobjectN t);
これには、実行時に新しい型を追加できないという一般的なバージョンと比較して問題があります。コンテナーを解決するために、GetPropsGeneric の DI コンテナーでできる狡猾な何かがありますか? ありがとう!