Generic Interface as constructor parameter for any derived T

时间:2015-06-25 19:09:01

标签: c# generics interface

Effectively, I don't much care about the derived endpoints here. Everything I need is base. I just want to to be able to pass in any IClient, and use its method, regardless of what the derived endpoint is. Disclaimer: Its very possible that in my effort to remove the extra stuff, I simplified this into not exactly the same thing. I have the following constructor public SomeClass(????? client) { _client = client; } public SomeMethod<TEndPoint>(SpecialObject o, TEndPoint e) where TEndPoint: Endpoint { Validate(o); //Do OtherStuff _client.UploadToClient(o, e) } The interface is as follows public interface IClient<TEndpoint> where TEndpoint: Endpoint { TEndpoint UploadToClient(obj o, endpoint e) } And I have a few implementations public class Client1: IClient<Endpoint1> public class Client2: IClient<Endpoint2> Are there any patterns/examples to get me to a point of being able to use a generic interface as a parameter without specifying a specific type? Adding on, I can design around some things, Really the main goal is that I just Don't want to make SomeCase generic, but do want to be able to cleanly and dynamically accept anything that implements IClient<>.

2 个答案:

答案 0 :(得分:1)

我看不出这是如何起作用的。没有办法阻止这种情况发生。

SomeClass myInstance = new SomeClass(new Client1());
Endpoint2 e2 = new Endpoint2();
myInstance.SomeMethod<Endpoint2>(o, e2);

请注意myInstance因其构造而只能处理Endpoint1,但它允许我使用Endpoint2调用SomeMethod,即使客户端会失败。如果你愿意放弃静态类型安全,你可以只声明所有内容dynamic并将其称为一天。

答案 1 :(得分:1)

假设您的界面可以修改。以下不能解决您的问题吗?

public interface IClient
{
    void UploadToClient<TEnd>(obj o, TEnd endpoint) where TEnd: Endpoint;
}