将对象转换为通用接口 [英] 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 a function which returns AdminRateShift as an Object:
IRelativeTo<IObject> = getObjectThatImplementsRelativeTo(); // returns Object
通过针对接口编程,我可以做我需要做的事情,但我实际上无法将 Object 转换为 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
是 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);
而不是
DoSomething<SomeType>(foo);
这两种方法都有好处.
这篇关于将对象转换为通用接口的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!