【发布时间】:2017-09-01 06:07:08
【问题描述】:
我正在尝试访问子类中的泛型类型属性。在下面的示例中,我重新创建了我的问题。是否有解决此问题的方法,或者根本不可能?提前致谢!
编辑:不能将集合声明为 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?
}
}
}
【问题讨论】:
-
它们继承自同一个抽象类(我们称之为
AbstractModel)。但不可能将集合声明为A<AbstractModel>。已经试过了。 -
@GoosvandenBekerom 我想我已经解决了你的问题,请看我的回答
标签: c# generics inheritance collections