保存从列表中选择的项目

时间:2018-02-28 07:40:23

标签: c# list function

主要课程:

public class Main 
{
    private string param;
    public Main(string param) { this.param = param; }

    public List<Foo> Foos
    {
        get {return GetFoos();}

        // add functionality of saving Foo (single item, not the whole list) here?
    }

    private List<Foo> GetFoos()
    {
        List<Foo> x = new List<Foo>();
        return x;
    }

    public class Foo
    {
        public int Id { get; set; }
        public string Name { get; set; }
        // or maybe here?
    }
}

测试类:

public class Test
{
    public Test()
    {
       var main = new Main("hi!");

       // usage 1
       main.Foos.Find(p => p.Id == 1).Save(); // method visible here

       var foo = new Main.Foo();
       // usage 2
       foo.Save(); // method not visible here
    }
}

代码中的评论基本上都说明了一切:
1.我想实现对象Foo的Save()方法 2.方法只有在从列表中选取Foo对象时才能调用(用法1)。
3.方法不能从单独创建的Foo对象中调用(用法2) 4.方法必须使用在主类初始化期间传递的属性 param 的私有值。

1 个答案:

答案 0 :(得分:1)

您可以使用界面隐藏方法保存。 为此,必须显式实现Save方法。 此外,您需要一个指向主对象的链接。在您的子类Foo中,您可以直接从Main访问private属性。

接口:

public interface IFoo
{
    int Id { get; set; }
    string Name { get; set; }

    void Save();
}

类别:

public class Main
{
    private string param;
    private List<IFoo> foos = new List<IFoo>();

    public Main(string param) { this.param = param; }

    public List<IFoo> Foos
    {
        get { return this.foos; }
    }

    public void AddFoo(int pnId, string pnName)
    {
        this.foos.Add(new Foo(this) { Id = pnId, Name = pnName });
    }

    public class Foo : IFoo
    {
        private Main moParent;

        public Foo() { }

        public Foo(Main poParent)
        {
            this.moParent = poParent;
        }

        public int Id { get; set; }
        public string Name { get; set; }

        //Implement interface explicitly
        void IFoo.Save()
        {
            if (this.moParent == null)
                throw new InvalidOperationException("Parent not set");

            Console.WriteLine($"Save with Param: {this.moParent.param}, Id: {this.Id} Name: {this.Name}");
            //Save Item
        }
    }
}

用法:

var main = new Main("hi!");

main.AddFoo(1, "Foo1");
// usage 1
main.Foos.Find(p => p.Id == 1).Save(); // method visible here

var foo = new Main.Foo();
// usage 2
//foo.Save(); // Save is not visible here