Objects of interface, but constraint on type implementing the interface
I've a generic method with a constraint like below:
private string GetResult<T>(T myObject) where T : IDoSomething<T>
{
......
}
Now, the problem is that the IDoSomething
is im开发者_高级运维plemented by the classes and not by classes interface and moreover the objects are always created using the interface as their type and not the class like:
IClassA myObject = new ClassA();
So, whenever the generic method is called, a cast must be made on myObject
to forward it as a parameter.
Is there a way to avoid the cast and make the code work? (except the option of inheriting IDoSomething
in IClassA
)
No, I don't think you can avoid the cast, since the interface IClassA
is not related in any way to IDoSomething
.
Just the fact that some class that implements one interface also happens to implement another interface doesn't make the two interfaces compatible.
Even the assignment of a IClassA
object back to a ClassA
variable requires a explicit cast.
No, there's no way to avoid the cast in the way that you're doing it.
If you don't want IDoSomething<T>
and IClassA
to be related by extension and you don't want to use a variable typed with the concrete class, then there isn't any information for the compiler to use to infer that your object implements the right interface for the method without using a cast.
It depends. Are you just trying to get T? In that case, you could do:
private static string GetResult<T>(IDoSomething<T> myObject) {}
Then T
will be inferred correctly from the interface (since IClassFoo
will always inherit from it) and you won't have to cast.
If you want to pass it as T
, though AND not have to cast it, then you're out of luck, there's not a relationship you can exploit.
精彩评论