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
. List<Bar>, , List<Baz>, List<> .
List<Bar>
List<Baz>
List<>
- , IEnumerable<Bar> virtual, SubFoo, IEnumerable<Baz>.
IEnumerable<Bar>
virtual
SubFoo
IEnumerable<Baz>
, , (, XML), virtual protected CreateBar(), bar LoadData() Bar . SubFoo Baz. SubFoo base.LoadData() Baz, Baz, Bar.
virtual protected CreateBar()
Bar
Baz
base.LoadData()
XML-, !
, , , , , Bar :
public List<TBar> LoadData<TBar>() where TBar : Bar, new() { // return a list populated with `new TBar()`; }
:
var newBars = Foo.LoadData<NewBar>();
- , Bar NewBar, List<IBar>.
List<IBar>
, object .
object
LoadData() . factory.
LoadData()
factory Bar, , Bar NewBar. , , , Snowbear.
NewBar
, . , . , IBar, .
msdn, .
(!), . ?
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);