Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

I have the following 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>

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

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
221 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
}

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);

There are benefits to both approaches.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...