解决方案1
您可以通过使用通用接口来解决此问题。该接口将由您的帮助程序(createGenericClass
)类实例使用,并且您的其他接口也将使用您希望传递的接口。我们称之为IBaseService
。
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);
}
所以,你可以实例化助手类是这样的:
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
}
}
注:也有几个步骤,你可以用它来简化你的使用辅助类,如做没有泛型的辅助类static(也许是Singleton),仅在方法上使用泛型。这样你就不需要实例化类。
然而,这些“简化”修改性能和可用性将取决于你的目标,在使用的情况下,对数据和其他管理类您正在使用等工作..
解决方案2 - (你的任务可以在没有泛型的情况下解决)
你说你不想转换收到的实例。既然你想在这些实例上调用不同的方法,你可以通过在你的helper类上调用不同的方法来调用它们。在这种情况下,你并不需要泛型。
这将完成这项工作,而不使用IBaseService
甚至泛型。
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);
}
”不行“,你能告诉我们会发生什么吗?如果编译器抱怨,你需要告诉我们实际的编译器错误。 –