开发者

Interfaced function returning type of implementing class

I am looking to implement an interface which has a function which will return the type of the base class without using a generic interface. Is this possible?

class MyClass : MyInterface<MyClass> // Would rather use one 开发者_运维技巧below

class MyClass : MyInterface   // Functions already know to use MyClass


If I understand your question correctly, your only choice without generics is to use reflection to do this.


You would have to do something like this:

interface MyInterface
{
    Type GetBaseType();
}

But at that point it would be simpler to call instance.GetType() since that is what the implementation of this method would most likely look like.

If by "type" you don't mean the reflected type but rather that you wish to be able to use the type from the interface statically at compilation time then you will need to make the interface generic.


You achieve it like this:

interface IUserService : IService<User>

then your class would be:

class UserService : IUserService


Either

  1. You hard code the return type as MyClass

  2. You define the return type as MyInterface and then in the implementation of MyClass you can return a MyClass. The caller won't know what it's getting, but could use typeof to find out.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜