我在使用泛型的地方实现了多个接口(interface)。下面是我的代码
public class createGenericClass<T> where T : IWebService,IVoiceService
{
public void CallDoSomeThing(T t, int x, int y)
{
t.DoSomeThing(x, y);
}
public void CallDoSomeThingElse(T t, int a, float b)
{
t.DoSomeThingElse(a, b);
}
}
public interface IWebService
{
void DoSomeThing(int x, int y);
}
public interface IVoiceService
{
void DoSomeThingElse(int a, float b);
}
public class Web_Service : IWebService
{
public void DoSomeThing(int x, int y)
{ }
}
public class Voice_Service : IVoiceService
{
public void DoSomeThingElse(int a, float b)
{ }
}
现在,我无法在 Main 方法中创建主类的实例。我正在尝试,但我做不到。
class Program
{
static void Main(string[] args)
{
createGenericClass<IWebService> obj = new createGenericClass<IWebService>();
}
}
请提出建议。
最佳答案
解决方案一
您可以使用通用接口(interface)解决此问题。该接口(interface)将由您的助手 (createGenericClass
) 类实例使用,并且还将由您希望传递的其他接口(interface)使用。我们称它为 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
}
}
注意:另外,您可以使用几个步骤来简化帮助程序类的使用,例如在没有泛型的情况下使帮助程序类静态化(可能是单例),并且仅在方法上使用泛型。这样你就不需要实例化类了。
然而,这些“简化”修改的性能和可用性将取决于您的目标、使用环境、数据和您正在使用的其他管理器类等。
解决方案 2 - (您的任务可以在没有泛型的情况下解决)
你说你不想转换接收到的实例。由于您想在这些实例上调用不同的方法,因此您通过在帮助类上调用不同的方法来调用它们。在这种情况下,您实际上并不需要泛型。
这将完成这项工作,无需使用 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);
}
关于c# - 通用的多个接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39524207/