windows store应用程序-绕过c#的限制并传递子元素集合

本文关键字:集合 元素 应用程序 store 绕过 windows | 更新日期: 2023-09-27 17:50:32

在我的Windows Store应用程序中,我使用c# 5.0。我需要通过传递子类集合来调用基类集合的方法:

    public class Foo // base class
    {
         public int fooVariable = 1;
         public void fooMethod(){....};  
    }
    public class Bar:Foo // child class
    public void DoSomething(Foo foo)
    public void DoSomething(List<Foo> foos)
    {
        foreach (var foo in foos)
        {
            Debug.WriteLine(foo.i);  //access to variable
            foo.fooMethod();         //access to method
            foo.i = 10;              //!!!i can change variable!!!
        }
    }
    private List<Bar> _list;
    public void Call()
    {
        DoSomething(new Bar());         // ok
        _list = new List<Bar>();
        list.Add(new Bar());            // I can add a lot of items.
        DoSomething(list);              // not ok
        foreach (var foo in foos)
        {
            Debug.WriteLine(foo.i);  // in console I need to see '10'
        }
    }

有可能绕过这样的限制吗?如果是,怎么做?

乌利希期刊指南

DoSomething中,我需要完全访问所有公共方法/变量(读/写)/属性(读/写)

windows store应用程序-绕过c#的限制并传递子元素集合

看起来DoSomething(List<Foo> foos)实际上只需要遍历列表。可以改成:

public void DoSomething(IEnumerable<Foo> foos)
{
    // Body as before
}

现在您可以将List<Bar>传递给该方法,因为IEnumerable<T>T中是协变的。