Can you define an interface so that the class that implements it must contain a member that also belongs to this class?

Essentially, I want it to be a class that can contain a list of references to instances of the same type. Something like the following:

interface IAccessibilityFeature { List<IAccessibilityFeature> Settings { get; set; } } class MyAccess : IAccessibilityFeature { List<MyAccess> Settings { get; set; } } 

I know that this will not compile, because the interface explicitly says that my Settings should be of type List<IAccessibilityFeature> . What I need is some guidance on the right way to achieve what I'm trying to do in the MyAccess class.

+6
source share
2 answers

Try the following:

 interface IAccessibilityFeature<T> where T : IAccessibilityFeature<T> { List<T> Settings { get; set; } } class MyAccess : IAccessibilityFeature<MyAccess> { List<MyAccess> Settings { get; set; } } 
+14
source

This can be done with:

 interface IAccessibilityFeature<T> { List<T> Settings { get; set; } } class MyAccess : IAccessibilityFeature<MyAccess> { List<MyAccess> Settings { get; set; } } 
+3
source

Source: https://habr.com/ru/post/907362/


All Articles