如何在接口中使用通用委托
我正在尝试创建一个包含通用委托的接口。然后,我希望实现该接口的类决定实际的类型方法,或者最好返回另一个委托。
下面是一些描述我想要实现的目标的代码。
public delegate void GenericMethod<T>(T arg);
public delegate void StringMethod(string str);
public delegate void ByteMethod(byte bt);
public interface ITest
{
GenericMethod<T> someMethod;
}
public class TestA : ITest
{
public GenericMethod<string> someMethod
{
get
{
return stringMethod; //which is of type StringMethod(string str), defined above
}
}
}
public class TestB : ITest
{
public GenericMethod<byte> someMethod
{
get
{
return byteMethod; //which is of type ByteMethod(byte bt);, defined above
}
}
}
这可能吗?或者说不可能以这种方式更换代表?
I'm trying to create an interface holding a generic delegate. I then want the classes implementing the interface to decide the actual type method, or preferably even return another delegate.
Below are some code describing what I'm trying to acheive.
public delegate void GenericMethod<T>(T arg);
public delegate void StringMethod(string str);
public delegate void ByteMethod(byte bt);
public interface ITest
{
GenericMethod<T> someMethod;
}
public class TestA : ITest
{
public GenericMethod<string> someMethod
{
get
{
return stringMethod; //which is of type StringMethod(string str), defined above
}
}
}
public class TestB : ITest
{
public GenericMethod<byte> someMethod
{
get
{
return byteMethod; //which is of type ByteMethod(byte bt);, defined above
}
}
}
Is this possible? Or is it impossible to switch delegates in such a manner?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
由于继承原则,您不能这样做。所有在 ITest 中工作的东西都应该在派生类/接口中工作。这意味着,如果我能够
在 ITest 中使用(查看 int),我应该能够在 TestA 和 TestB 中使用它。您试图忽略此限制
You cannot do this because of inheritance principles. All, that works in ITest, should work in derived classes/interfaces. That means, if I'm able to use
(look at int) in ITest, I should be able to use it in TestA and TestB. You are trying to ignore this restriction
我认为如果不使接口通用,这是不可能的。常见的实现是:
或者,如果您想真正拥有一个非泛型接口,请使用:
您还可以查看两个接口
IEnumerable
和IEnumerable
了解如何组合通用和非通用接口。当您不关心具体类型时,只需显式实现非泛型接口即可使用。I do not think that this is possible without making the interface generic. The common implementation would be:
Or, if you want to actually have a non-generic interface, use:
You can also take a look at two interfaces
IEnumerable
andIEnumerable<T>
to see how you can combine both generic and non-generic interfaces. Just implement the non-generic interface explicitly for use when you do not care about the concrete type.