C # Classes

I have a Foo class that has a function that looks like this

List<Bar> LoadData();

Both Foo and Bar are in the library that I want to reuse in other projects. Now I am working on a new project and I want to subclass Bar. Let me call him NewBar.

What is a simple and flexible way to get Foo.LoadData to return a NewBar list? I think a factory is required or maybe just a delegate function. Can anyone provide an example?

Thanks Andy

+5
source share
6 answers

. List<Bar>, , List<Baz>, List<> .

- , IEnumerable<Bar> virtual, SubFoo, IEnumerable<Baz>.


UPDATE

, , (, XML), virtual protected CreateBar(), bar LoadData() Bar . SubFoo Baz. SubFoo base.LoadData() Baz, Baz, Bar.

, ,

XML-, !

+1

, , , , , Bar :

public List<TBar> LoadData<TBar>()
    where TBar : Bar, new()
{
    // return a list populated with `new TBar()`;
}

:

var newBars = Foo.LoadData<NewBar>();
+3

- , Bar NewBar, List<IBar>.

, object .

+2

LoadData() . factory.

factory Bar, , Bar NewBar. , , , Snowbear.

+1

, . , . , IBar, .

msdn, .

0

(!), . ?

public interface IBarFactory
{
    Bar Create();
}

LoadData :

List<Bar> LoadData(IBarFactory Factory)
{
    List<Bar> MyList = new List<Bar>();

    if (Factory == null)
    {
        MyList.Add(new Bar());
    }
    else
    {
        MyList.Add(Factory.Create());
    }

    // etc, etc
}

Then I just need to create the following:

public class BazFactory : IBarFactory
{
    Bar Create() { return new Baz() };
}

Finally call it:

MyList = LoadData(BazFactory);
0
source

All Articles