保存从列表中选择的项目

问题描述 投票:0回答:1

主要课程:

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的私有值。

c# list function
1个回答
1
投票

您可以使用界面隐藏方法Save。为此,必须显式实现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
© www.soinside.com 2019 - 2024. All rights reserved.