C # - Access property in inheritance class

I am trying to access a typical typed property in a child class. In the example below, I recreated my problem. Is there a workaround for this problem, or is it just not possible? Thanks in advance!

EDIT: It is not possible to declare a collection as A<Model>or A<T>.

public abstract class Model {
    public int Id { get; }
}

public interface I<T> where T: Model {
    ICollection<T> Results { get; }
}

public abstract class A { }

public class A<T> : A, I<T> where T : Model {
    public ICollection<T> Results { get; }
}

public class Example {

    A[] col;

    void AddSomeModels() {
        col = new A[] {
            new A<SomeModel>(),
            new A<SomeOtherModel>()
        }
    }

    void DoSomethingWithCollection() {
        foreach (var a in col) {
            // a.Results is not known at this point
            // is it possible to achieve this functionality?
        }
    }
}
+4
source share
1 answer

You cannot do what you want without any compromises.

First of all, you should make your code I<T>covariant in T:

public interface I<out T> where T : Model
{
    IEnumerable<T> Results { get; }
}

, , T . ICollection<T> T, Results IEnumerable<T>.

, , , :

public void DoSomethingWithCollecion()
{
    var genericCol = col.OfType<I<Model>>();

    foreach (var a in genericCol )
    {
        //a.Results is now accessible.
    }
}
+5

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


All Articles