C# - 继承类的Access属性

Goo*_*rom 4 c# generics collections inheritance

我正在尝试访问子类中的泛型类型属性.在下面的例子中,我重新创建了我的问题.是否有解决此问题的方法,或者根本不可能?提前致谢!

编辑:无法将集合声明为A<Model>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?
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

InB*_*een 5

没有妥协,你不能做你想要的.

首先,您需要使您的界面I<T>协变T:

public interface I<out T> where T : Model
{
    IEnumerable<T> Results { get; }
}
Run Code Online (Sandbox Code Playgroud)

因此,第一个妥协是T只能是输出.ICollection<T>是不是协变的T,所以你就需要改变的类型ResultsIEnumerable<T>.

执行此操作后,以下是类型安全的,因此允许:

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

    foreach (var a in genericCol )
    {
        //a.Results is now accessible.
    }
}
Run Code Online (Sandbox Code Playgroud)