[英]How to use a generic delegate in an interface
我正在尝试创建一个包含通用委托的接口。 然后,我希望实现该接口的类决定实际的类型方法,或者最好甚至返回另一个委托。
以下是一些代码,描述了我要达到的目标。
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
}
}
}
这可能吗? 还是不可能以这种方式切换代表?
我认为如果不使接口通用,就不可能做到这一点。 常见的实现方式是:
public interface ITest<T>
{
GenericMethod<T> someMethod;
}
或者,如果您想真正拥有一个非通用接口,请使用:
public interface ITest
{
GenericMethod<object> someMethod;
}
您还可以查看IEnumerable
和IEnumerable<T>
两个接口,以了解如何组合通用接口和非通用接口。 只要不关心具体类型,就可以显式实现非泛型接口以供使用。
public delegate void GenericMethod<T>(T arg);
public delegate void StringMethod(string str);
public delegate void ByteMethod(byte bt);
public interface ITest<T>
{
GenericMethod<T> someMethod { get; };
}
public class TestA : ITest<string>
{
public GenericMethod<string> someMethod
{
get
{
return stringMethod; //which is of type StringMethod(string str), defined above
}
}
}
public class TestB : ITest<byte>
{
public GenericMethod<byte> someMethod
{
get
{
return byteMethod; //which is of type ByteMethod(byte bt);, defined above
}
}
}
由于继承原则,您无法执行此操作。 所有可以在ITest中工作的方法都应该在派生类/接口中工作。 也就是说,如果我能够使用
GenericMethod<int> someMethod
(看int)在ITest中,我应该能够在TestA和TestB中使用它。 您正在尝试忽略此限制
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.