Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
240 views
in Technique[技术] by (71.8m points)

c# - Casting an object to a generic interface

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

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

1 Reply

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...