C# - 在继承类中访问属性

4
我正在尝试在子类中访问一个泛型类型的属性。在下面的示例中,我重新创建了我的问题。这个问题有解决方法吗,还是根本不可能实现?谢谢!

编辑:无法将集合声明为 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>。已经尝试过了。 - Goos van den Bekerom
@GoosvandenBekerom 我想我已经解决了你的问题,请查看我的答案。 - Pablo Recalde
1个回答

5

如果不做出一些妥协,您就无法实现自己的意图。

首先,您需要使接口I<T>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.
    }
}

+1 这实际上非常聪明。不过我不知道原帖作者对于用 IEnumerable<T> 替换 ICollection<T> 的想法会有什么感觉。 - Dave Becker
妥协是我很乐意做出的。这个功能非常好用,谢谢! - Goos van den Bekerom

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接