解決策1
この問題は、共通のインターフェイスを使用して解決できます。そのインターフェイスはヘルパー(createGenericClass
)クラスのインスタンスによって使用され、渡す他のインターフェイスでも使用されます。それをIBaseService
としましょう。
class Program
{
static void Main(string[] args)
{
var obj = new createGenericClass<IBaseService>();
obj.CallDoSomeThing(new Web_Service(), 1, 2); // works well
obj.CallDoSomeThingElse(new Voice_Service(), 3, 4); // works well
}
}
注:
public class createGenericClass<T>
where T : IBaseService // telling T can be only IBaseService and inherited stuff.
{
public void CallDoSomeThing(T t, int x, int y)
{
(t as IWebService)?.DoSomeThing(x, y); // casting and validating
}
public void CallDoSomeThingElse(T t, int a, float b)
{
(t as IVoiceService)?.DoSomeThingElse(a, b); // casting and validating
}
}
public interface IBaseService{} // only gives a common parent to other interfaces. Common properties, methods can be included here.
public interface IWebService : IBaseService // inheriting the common interface
{
void DoSomeThing(int x, int y);
}
public interface IVoiceService : IBaseService // inheriting the common interface
{
void DoSomeThingElse(int a, float b);
}
だから、あなたはこの方法あなたのヘルパークラスをインスタンス化でき、また、そのような作りなど、あなたのヘルパークラスの使用方法を簡素化するために使用できるいくつかのステップがあり、ヘルパークラス静的(多分シングルトン)ジェネリックスを使用せずジェネリックメソッドのみをメソッドで使用します。このようにして、クラスをインスタンス化する必要はありません。しかし
、これらは変更のパフォーマンスと使いやすさは、あなたがなどで作業しているデータや他のマネージャクラスに、利用状況の文脈に、あなたの目標に依存する「簡素化」..
ソリューション2 - (あなたの仕事はジェネリックスなしで解決できる)
あなたは受け取ったインスタンスをキャストしたくないと言った。これらのインスタンスで異なるメソッドを呼び出す場合は、ヘルパークラスのさまざまなメソッドを呼び出すことでそれらを呼び出すことになります。この場合、Genericsは本当に必要ありません。
これは、IBaseService
やGenericsを使わずに仕事をします。
public class createGenericClass
{
public void CallDoSomeThing(IWebService t, int x, int y)
{
t.DoSomeThing(x, y);
}
public void CallDoSomeThingElse(IVoiceService t, int a, float b)
{
t.DoSomeThingElse(a, b);
}
}
ソリューション3から(ここで推奨されていない二重ジェネリックものは、)
あなたはそれを求めてきましたので:
public class createGenericClass<T, V>
where T: IWebService
where V: IVoiceService
{
public void CallDoSomeThing(T t, int x, int y)
{
t.DoSomeThing(x, y);
}
public void CallDoSomeThingElse(V t, int a, float b)
{
t.DoSomeThingElse(a, b);
}
}
用途:
static void Main(string[] args)
{
var obj = new createGenericClass<IWebService, IVoiceService>();
obj.CallDoSomeThing(new Web_Service(), 1, 2);
obj.CallDoSomeThingElse(new Voice_Service(), 3, 4);
}
"できません "、どうしたらいいのですか?コンパイラに不満がある場合は、実際のコンパイラエラーを教えてください。 –