Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inherit from generic type as interface

I am attempting to do something similar to:

public interface IView<T> : T where T : class 
{ 
    T SomeParam {get;} 
}

So that i can later do

public class SomeView : IView<ISomeView> 
{
}

Is it possible to specify inheritance using generics in this way or do i have to go the long way round and explicitly specify both interfaces when defining the class and do:

public interface IView<T> 
{ 
    T SomeParam {get;} 
}
public class SomeView : IView<ISomeView>, ISomeView 
{
}
like image 601
bizzehdee Avatar asked Feb 07 '14 14:02

bizzehdee


People also ask

Can a generic type be an interface?

Generic Interfaces in Java are the interfaces that deal with abstract data types. Interface help in the independent manipulation of java collections from representation details. They are used to achieving multiple inheritance in java forming hierarchies.

Is it possible to inherit from a generic type?

An attribute cannot inherit from a generic class, nor can a generic class inherit from an attribute.

Can an interface be inherited?

Interfaces can inherit from one or more interfaces. The derived interface inherits the members from its base interfaces. A class that implements a derived interface must implement all members in the derived interface, including all members of the derived interface's base interfaces.

Can an interface have a generic type java?

Java Generic Interface In similar way, we can create generic interfaces in java. We can also have multiple type parameters as in Map interface. Again we can provide parameterized value to a parameterized type also, for example new HashMap<String, List<String>>(); is valid.


1 Answers

This isn't possible, but your goal may be achievable with conversion operators. It seems that what you're trying to do is make it possible to pass an IView<T> as the T object which it contains. You could write a base class like this:

public abstract class ViewBase<T> {
    public abstract T SomeParam { get; }

    public static implicit operator T(ViewBase<T> view) {
        return view.SomeParam;
    }
}

Then, if you define a class like:

public class SomeView : ViewBase<ISomeView> { }

It can be accepted anywhere an ISomeView is expected:

ISomeView view = new SomeView();
like image 76
nmclean Avatar answered Oct 14 '22 02:10

nmclean