投对象的通用接口 [英] Casting an object to a generic interface
问题描述
我有以下接口:
internal interface IRelativeTo<T> where T : IObject
{
T getRelativeTo();
void setRelativeTo(T relativeTo);
}
和一堆类,(应该)实现它,如:
and a bunch of classes that (should) implement it, such as:
public class AdminRateShift : IObject, IRelativeTo<AdminRateShift>
{
AdminRateShift getRelativeTo();
void setRelativeTo(AdminRateShift shift);
}
我意识到,这三个是不一样的:
I realise that these three are not the same:
IRelativeTo<>
IRelativeTo<AdminRateShift>
IRelativeTo<IObject>
但尽管如此,我需要的方式与所有不同的类,如AdminRateShift(和FXRateShift,DetRateShift工作)应该都实现IRelativeTo。比方说,我有返回AdminRateShift为对象的功能:
but nonetheless, I need a way to work with all the different classes like AdminRateShift (and FXRateShift, DetRateShift) that should all implement IRelativeTo. Let's say I have an function which returns AdminRateShift as an Object:
IRelativeTo<IObject> = getObjectThatImplementsRelativeTo(); // returns Object
通过针对接口编程,我可以做什么,我需要,但我可以'T居然投的对象IRelativeTo这样我就可以使用它。
By programming against the interface, I can do what I need to, but I can't actually cast the Object to IRelativeTo so I can use it.
这是一个简单的例子,但我希望它会澄清什么,我试图做的。
It's a trivial example, but I hope it will clarify what I am trying to do.
推荐答案
如果我理解的问题,那么最常用的方法是申报非通用底座接口,即
If I understand the question, then the most common approach would be to declare a non-generic base-interface, i.e.
internal interface IRelativeTo
{
object getRelativeTo(); // or maybe something else non-generic
void setRelativeTo(object relativeTo);
}
internal interface IRelativeTo<T> : IRelativeTo
where T : IObject
{
new T getRelativeTo();
new void setRelativeTo(T relativeTo);
}
另一个选择是让你在很大程度上泛型代码...即你有像
Another option is for you to code largely in generics... i.e. you have methods like
void DoSomething<T>() where T : IObject
{
IRelativeTo<IObject> foo = // etc
}
如果在 IRelativeTo< T> ;
是一个参数 DoSomething的()
,然后的一般的,你不需要自己指定泛型类型参数 - 编译器会推断出它 - 即
If the IRelativeTo<T>
is an argument to DoSomething()
, then usually you don't need to specify the generic type argument yourself - the compiler will infer it - i.e.
DoSomething(foo);
而不是
rather than
DoSomething<SomeType>(foo);
有这两种方法的好处。
这篇关于投对象的通用接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!