Suppose am in a class
`public class Foo{
//some fields
ArrayList fooList = new ArrayList<>();
//methods
Public void addFoo(){
//some code
fooList.add(this);
}
}`
wrote a method call addFoo() in 'foo' class. So now my question is what am I doing when I say arraylistObject.add(this) inside addFoo()... What am I actually doing.
Please find the below usecase which might help you.
A data structure that stores a collection of the same structure will create a tree implicitly.
public class TreeSample {
private String value;
private List<TreeSample> childNodes;
TreeSample(String value) {
this.value = value;
childNodes = new LinkedList<TreeSample>();
}
public void addChild(TreeSample childTree) {
this.childNodes.add(childTree);
}
}
So, the client code can construct a tree data structure, by adding child trees to the parent nodes.
Related
I have a base abstract class, which aggregates a bunch of items in a collection:
abstract class AMyAbstract
{
List<string> Items { get; private set; }
public AMyAbstract(IEnumerable<string> items)
{
this.Items = new List<string>(items);
}
}
There are a lot of subclasses, let's name them Foo, Bar, Baz, etc. They all are immutable. Now I need a merge() method, which will merge items of two objects like this:
abstract class AMyAbstract
{
// ...
public AMyAbstract merge(AMyAbstract other)
{
// how to implement???
}
}
Foo foo1 = new Foo(new string[] {"a", "b"});
Bar bar1 = new Bar(new string[] {"c", "d"});
Foo fooAndBar = foo1.merge(bar1);
// items in fooAndBar now contain: {"a", "b", "c", "d"}
Since the objects are immutable, the merge() method should not change the state of items field, but instead it should return a new object of the class uppon which it is called. My question is: how to judiciously implement the merge() method?
Problem 1: AMyAbstract is clearly not aware of specific constructors of the subclasses (dependency inversion principle), thus I cannot (or can I?) create instance of the sub class in a super class.
Problem 2: Implementing merge() method in each of the subclasses is a lot of code repetition (DRY rule).
Problem 3: Extracting the merge() logic to a entirely new class does not solve the DRY rule problem. Even using the visitor pattern it is a lot of copy/paste.
The problems presented above rule out any idea of implementation I might have had before I read about SOLID. (my life has been miserable since then ;)
Or is there an entirely different, out-of-the-box approch to achieve the merge of such objects?
I'd appreciate answer in C#, Java or even PHP.
EDIT: I think I left out a piece of valid information: event though there are a lot of different sub classes, they can (should) only be constructed in two, maybe three ways (as an implication of the single responsibility principle):
parameterless constructor
a constructor which accepts one IEnumerable<T> argument
a constructor which accepts array and some other modifier
This would put the visitor pattern back on the tablie if I could put a constraint on the constructors - for example by defining a constructor in an interface. But this is possible only in PHP. In Java or C# a constructor signature cannot be enforced, thus I cannot be certain of how I would instantiate a subclass. This is a good rule in general, because one could never predict of how author of the subclass would like the object be constructed, but in this particular case it might have been helpful. So a helper question would be: can I somehow enforce how a class is instantiated? Builder pattern sounds like way too much in this simple case, or does it?
You are right about dependency inversion rule and code duplication problems.
You can write the core implementation of the merge logic in your abstract class and give out the task of creating a new instance to the derived classes. Create an abstract method in your abstract class that will force all the children to implement it. The purpose is this method is to create a new instance of the class and return it. This method will be used by the super class to get a new instance and do the merging.
The resultant java code will look something like this
abstract class AMyAbstract {
// ...
public AMyAbstract merge(AMyAbstract other) {
AMyAbstract obj = getNewInstance();
// Do the merge
// Return the merged object.
}
protected abstract AMyAbstract getNewInstance();
}
class foo extends AMyAbstract {
protected foo getNewInstance() {
// Instantiate Foo and return it.
}
}
Hope this helps..
OBSOLETE, kept for reference (and shows how I arrived at the final solution), see code after EDIT below
I would say the builder pattern is the way to go. We just need a builder which keeps the instance but modifies the one field that needs to be changed.
If one wants to obtain (as shown in your code)
Foo fooAndBar = foo1.merge(bar1);
an additional generic type definition is needed (thus defining class AMyAbstract <T>) to be able to still produce the correct final type (instead of just seeing AMyAbstract as type for the fooAndBar) in the above call.
Note: merge method was renamed to MergeItems in the code below to make clear what is merged.
I specified different constructors for Foo and Bar, so that it is clear that they do not need to have the same number of parameters.
Actually to be truly immutable, the list should not be directly returned in the Items property as it could be modified by the caller (using new List(items).AsReadOnly() produced a ReadOnlyCollection, so I just used this one).
Code:
abstract class AMyAbstract<T> where T : AMyAbstract<T>
{
public ReadOnlyCollection<string> Items { get; private set; }
protected AMyAbstract(IEnumerable<string> items)
{
this.Items = new List<string>(items).AsReadOnly();
}
public T MergeItems<T2>(AMyAbstract<T2> other) where T2 : AMyAbstract<T2>
{
List<string> mergedItems = new List<string>(Items);
mergedItems.AddRange(other.Items);
ButWithItemsBuilder butWithItemsBuilder = GetButWithItemsBuilder();
return butWithItemsBuilder.ButWithItems(mergedItems);
}
public abstract class ButWithItemsBuilder
{
public abstract T ButWithItems(List<string> items);
}
public abstract ButWithItemsBuilder GetButWithItemsBuilder();
}
class Foo : AMyAbstract<Foo>
{
public string Param1 { get; private set; }
public Foo(IEnumerable<string> items, string param1)
: base(items)
{
this.Param1 = param1;
}
public class FooButWithItemsBuilder : ButWithItemsBuilder
{
private readonly Foo _foo;
internal FooButWithItemsBuilder(Foo foo)
{
this._foo = foo;
}
public override Foo ButWithItems(List<string> items)
{
return new Foo(items, _foo.Param1);
}
}
public override ButWithItemsBuilder GetButWithItemsBuilder()
{
return new FooButWithItemsBuilder(this);
}
}
class Bar : AMyAbstract<Bar>
{
public string Param2 { get; private set; }
public int Param3 { get; private set; }
public Bar(IEnumerable<string> items, string param2, int param3)
: base(items)
{
this.Param2 = param2;
this.Param3 = param3;
}
public class BarButWithItemsBuilder : ButWithItemsBuilder
{
private readonly Bar _bar;
internal BarButWithItemsBuilder(Bar bar)
{
this._bar = bar;
}
public override Bar ButWithItems(List<string> items)
{
return new Bar(items, _bar.Param2, _bar.Param3);
}
}
public override ButWithItemsBuilder GetButWithItemsBuilder()
{
return new BarButWithItemsBuilder(this);
}
}
class Program
{
static void Main()
{
Foo foo1 = new Foo(new[] { "a", "b" }, "param1");
Bar bar1 = new Bar(new[] { "c", "d" }, "param2", 3);
Foo fooAndBar = foo1.MergeItems(bar1);
// items in fooAndBar now contain: {"a", "b", "c", "d"}
Console.WriteLine(String.Join(", ", fooAndBar.Items));
Console.ReadKey();
}
}
EDIT
Perhaps a simpler solution would be to avoid the builder class, and instead have
abstract T ButWithItems(List<string> items);
directly in the base class, and implementing classes would just implement it as currently the builders do.
Code:
abstract class AMyAbstract<T> where T : AMyAbstract<T>
{
public ReadOnlyCollection<string> Items { get; private set; }
protected AMyAbstract(IEnumerable<string> items)
{
this.Items = new List<string>(items).AsReadOnly();
}
public T MergeItems<T2>(AMyAbstract<T2> other) where T2 : AMyAbstract<T2>
{
List<string> mergedItems = new List<string>(Items);
mergedItems.AddRange(other.Items);
return ButWithItems(mergedItems);
}
public abstract T ButWithItems(List<string> items);
}
class Foo : AMyAbstract<Foo>
{
public string Param1 { get; private set; }
public Foo(IEnumerable<string> items, string param1)
: base(items)
{
this.Param1 = param1;
}
public override Foo ButWithItems(List<string> items)
{
return new Foo(items, Param1);
}
}
class Bar : AMyAbstract<Bar>
{
public string Param2 { get; private set; }
public int Param3 { get; private set; }
public Bar(IEnumerable<string> items, string param2, int param3)
: base(items)
{
this.Param2 = param2;
this.Param3 = param3;
}
public override Bar ButWithItems(List<string> items)
{
return new Bar(items, Param2, Param3);
}
}
class Program
{
static void Main()
{
Foo foo1 = new Foo(new[] { "a", "b" }, "param1");
Bar bar1 = new Bar(new[] { "c", "d" }, "param2", 3);
Foo fooAndBar = foo1.MergeItems(bar1);
// items in fooAndBar now contain: {"a", "b", "c", "d"}
Console.WriteLine(String.Join(", ", fooAndBar.Items));
Console.ReadKey();
}
}
I'm a bit late to the party but as you have yet to accept an answer I thought I would add my own.
One of the key points is that the collection should be immutable. In my example I have exposed IEnumerable to facilitate this - the collection of items is immutable outside of the instance.
There are 2 ways I see this working:
a public default constructor
an internal Clone template method similar to #naveen's answer above
Option 1 is less code but really it depends whether an instance of AMyAbstract with no items and no way to change the items is something you want to allow.
private readonly List<string> items;
public IEnumerable<string> Items { get { return this.items; } }
public static T CreateMergedInstance<T>(T from, AMyAbstract other)
where T : AMyAbstract, new()
{
T result = new T();
result.items.AddRange(from.Items);
result.items.AddRange(other.Items);
return result;
}
Seems to satisfy all of your requirements
[Test]
public void MergeInstances()
{
Foo foo = new Foo(new string[] {"a", "b"});
Bar bar = new Bar(new string[] {"c", "d"});
Foo fooAndBar = Foo.CreateMergedInstance(foo, bar);
Assert.That(fooAndBar.Items.Count(), Is.EqualTo(4));
Assert.That(fooAndBar.Items.Contains("a"), Is.True);
Assert.That(fooAndBar.Items.Contains("b"), Is.True);
Assert.That(fooAndBar.Items.Contains("c"), Is.True);
Assert.That(fooAndBar.Items.Contains("d"), Is.True);
Assert.That(foo.Items.Count(), Is.EqualTo(2));
Assert.That(foo.Items.Contains("a"), Is.True);
Assert.That(foo.Items.Contains("b"), Is.True);
Assert.That(bar.Items.Count(), Is.EqualTo(2));
Assert.That(bar.Items.Contains("c"), Is.True);
Assert.That(bar.Items.Contains("d"), Is.True);
}
Whether you ultimately choose a default constructor or a template method the crux of this answer is that the Items only need to be immutable on the outside.
A neat solution based on #AK_'s comment:
tldr: The basic idea is to create a multiple merge methods for each aggregated filed instead of using a merge method for entire object.
1) we'd want a special list type for the purpose of aggregating the items inside AMyAbstract instances, so let's create one:
class MyList<T> extends ReadOnlyCollection<T> { ... }
abstract class AMyAbstract
{
MyList<string> Items { get; private set; }
//...
}
The advantage here is that we have a specialized list type for our purpose, which we can alter later.
2) instead of having a merge method for entire object of AMyAbstract we would want to use a method which merly merges the items of that object:
abstract class AMyAbstract
{
// ...
MyList<T> mergeList(AMyAbstract other)
{
return this.Items.Concat(other.Items);
}
}
Another advatage we gain: decomposition of the problem of merging entire object. So instead we break it into a small problems (merging just the aggregated list in this case).
3) and now we can create a merged object using any specialized constructor we might think of:
Foo fooAndBar = new Foo(foo1.mergeList(bar1));
Instead of returning the new instance of entire object we return only the merged list, which in turn can be used to create object of target class. Here we gain yet another advantage: deferred object instantiation, which is the main purpose of creational patterns.
SUMMARY:
So not only this solution solves the problems presended in the question, but provides additional advantages presented above.
I have a class that only have main which read in some txt and do the algorithms.
my class is look like:
class doThejob{
public static void main(String args[]){
//*****start part A******
//do the reading from text file, and tokenize it
// process into the form I need,
//about 10-30 lines of codes
//******End of part A*****
//then run the algorithms
algorithm alg=new aglorithm();
Object output = alg.x(input);
//****Part B**** output to txt, about 10~40 lines
}
}
class algorithm{
private void a(Object x){
//do something
return (Object)result;
}
}
Can anyone tell me should I extract those part A and part B to a new class ,and then setup them as a public method .like below
class Io{
public Object readFromTxt(String path){
}
public void outputToTxt(String path){
}
}
And if I setup them , and then use it like below, is that more OOP?
class doThejob{
public static void main(String args[]){
Io dataProcess= new Io();
Object input = dataProcess.readFromTxt(args[0]);
algorithm alg=new aglorithm();
Object output =alg.x(input);
dataProcess.readFromTxt(args[1],output);
}
}
class algorithm{
private Object a(Object x){
//do something
}
}
Do it the way you fill is more readable.
Separating this in another class is according to the Single Responsability Principle. It will help making the code more readable and easy to change later on.
If you want to expand more on this, you could create an interface (eg.: IIO) for input and output. This way you can implement this interface in the IO class, renaming it to FileIO. Anytime you want to create another form of IO, like database access, you just have to create a DatabaseIO class that implements this interface and change the instance in the main method for this new type:
public interface IIO
{
string Read();
void Write(string text);
}
public class FileIO : IIO
{
string path;
public FileIO(string filePath)
{
path = filePath;
}
public string Read()
{
// read from file and return contents
}
public void Write(string text)
{
// write to file
}
}
public class SqlServerIO : IIO
{
SqlConnection conn;
public SqlServerIO(string connectionStringName)
{
// create the connection
}
public string Read()
{
// read from database
}
public void Write(string text)
{
// write to database
}
}
Extracting interfaces makes the code more maintenable by alowing to switch implementations anytime without messing with working code. It also facilitates unit testing.
I am having a bit of trouble understanding how I will design a class.
I want to be able to get n amount of System fields out onto a report alongside custom fields.
I want a simple method on an interface called:
ICollection<Field> GetFieldDefinitions();
Internally this should get all the fields that I need to show on the report.
A second method will return field and their values too:
ICollection<Field> GetFieldDefinitionsWithValues(T src);
T is the source of where the information for each field will be populated from, e.g. if I pass in Company, the field definition if it contains CompanyName, I will do a lookup on the Company table and retrieve the info and add it to the field.
public Class SystemFieldCompany
{
IDictionary<string,Field> list;
private readonly ValidationEngine _val;
public SystemFieldCompany(ValidationEngine val)
{
_val = val;
list = new Dictionary<string,Field>();
}
public ICollection<Field> GetFields()
{
list.add("id",new Field{name = "id", value = "5"});
list.add("nameofcompany",new Field{name = "nameofcompany", value = "super guys"});
return list.Values;
}
//pass in model object with values on it, set up fields, then pass back all fields
ICollection<Field> GetFieldsWithValues(T object);
}
Should this class above be a concrete class?
e.g. var fields = new FieldClass().GetFields();
or should I use composition? How can I do this via an interface?
Abstract Class is what your after
public abstract class FieldBase
{
ICollection<Field> _data=new List<Field>();
abstract void DoValidationOrSomething();
ICollection<Field> virtual GetFields() //perform validation internally - return back the object
{
DoValidationOrSomething();
return _data;
}
T virtual UpdateFields(ICollection<Field> fields); //pass in model object with values on it, set
{
_data.Clear();
_data.AddRange(fields);
}
up fields, then pass back all fields
ICollection<Field> virtual GetFieldsWithValues(T object)
{
return _data.Where(f=>f.Name=T);
}
}
then in your concrete
public class SomeTable:FieldBase
{
public void DoValidationOrSomething()
{
//per class validation here
}
}
I am looking for an elegant design for a problem analogous to the following:
A story can have a flexible hierarchical structure. It might consist of several books, each of which have chapters, each of which have sections, each of which contain text. Or, it might simply have sections (a short story for instance). Or it might just consist of chapters that have sections. In all situations, you mustn't be allowed to mix styles (so you couldn't add a chapter to a story based on books, you would have to add the chapter to the book itself).
I have come up with a couple of design solutions for this type of problem but they get messy. Is there a clean way to represent this so that, given a reference to a Story class I can get access to the content in a clear, systematic fashion?
Its kind of tricky situation because the concepts like "Books", "chapters", "sections", may have some common elements that suggest a class hierarchy or common interface implementation.
And at the same time, enough different to be handle as different classes / objects, at all, as the requirement of "so you couldn't add a chapter to a story based on books".
When dealing conceptualy with hierarchical objects, there are several approaches of how to turn them into into code, each one suits better to a particular situation.
1. Class Composition
There is a class or prototype for each concept, they may be related or not by inheritance or interfaces.
There are internal collections of the elements, and their operations can be restricted,
by methods.
// this one can be optional, not required,
// replaced by several parent classes,
// or replaced by interfaces
public class LibraryRootClassMaybe {
// members here
}
public class BookText extends LibraryRootClassMaybe {
// members here
} // class BookText
public class BookSection extends LibraryRootClassMaybe {
// element collection should not be public
List BookTexts;
public Book() {
this.BookTexts = new ArrayList();
}
public void addBookTest(BookText Item) {
// validation and casting from object to BookText
}
// members here
} // class BookSection
public class BookChapter extends LibraryRootClassMaybe {
// element collection should not be public
List BookSections;
public Book() {
this.BookSections = new ArrayList();
}
public void addBookTest(BookSection Item) {
// validation and casting from object to BookSection
}
// members here
} // class BookChapter
public class Book extends LibraryRootClassMaybe {
// element collection should not be public
List BookChapters;
public Book() {
this.BookChapters = new ArrayList();
}
public void addBookTest(BookText Item) {
// validation and casting from object to BookText
}
// members here
} // class Book
These approach is good when there are not many different classes, maybe 5.
2. The Tree Design Pattern.
These one applies when all elements will be equal if not similar,
usually same class or interface, usually a lot of items.
These one does not apply to your case, but,
I had to mention, to apply better.
Usually, a tree / hierarchical collection class, its used.
It could be a subclass of a generic / template tree collection,
or a subclass of a base tre collection,
that is intended to be replaced by child classes with particular members.
public class FileSystemRootClass {
public bool AmISystemRoot() {
// more
}
public bool AmIAFolder() {
// more
}
public bool AmIAFile() {
// more
}
public void addSystemRoot(string FileSystemName) {
// more
}
public void addFolder(string FileSystemName) {
// more
}
public void addFile(string FileSystemName) {
// more
}
// members here
}
3. The Hybrid.
These one is a combination of the previous two,
its used when there is a lot of related items,
its more complex, may use or not the Factory & Abstract Factory Patterns,
and its more common example are visual controls & widgets libraries.
import java.util.*;
public class WidgetsExample {
public static void main(String[] args) {
TreeSet <Widget> FormControls = new TreeSet<Widget>();
TextBoxWidget TextBox = new TextBoxWidget();
FormControls.add(TextBoxWidget);
ListBoxWidget ListBox = new ListBoxWidget();
FormControls.add(TextBoxWidget);
ButtonWidget Button = new ButtonWidget();
FormControls.add(Button);
} // class WidgetsExample
You may notice that I didn't use the "factory pattern" & "abstract factory",
due to require more code.
Good Luck.
Good OO design starts with thinking about Use Cases and not class hierarchies. This is a common mistake and tends to produce over-complicated designs.
First consider what you are building and write out a problem statement a description of the problem you are solving using English prose in the language of the problem domain.
Then consider making a mockup if the product is a UI.
Then you can start writing out use cases and start thinking about how objects will interact with each other.
It's called Object-oriented programming, not Class-oriented programming. Classes are the specification in code to manage/create/run all the objects in the system. I'd be thinking about objects and what they are doing. Classes are simply an implementation detail.
If your goal is to perform operations on hierarchies, you might want to consider using the Composite pattern. You could do something like have a Story object that can contain a list of Story objects. Each Story object would also have it's own type (book-collection,book,chapter,sub-chapter,paragraph,essay), and it's own attributes and methods (depending on your use cases).
I'd try something like this:
interface StoryElement<SE extends SubElements>{
List<SE> getContents()
}
class Story<T extends StoryElement>
class Book implements StoryElement<Chapter> ...
class Chapter implements StoryElement<Section> ...
class Section implements StoryElement<Text>
class Text implements StoryElement<Text> {... // ugly hack, don't know of a clean way to end the recursion with Java Generics
Now you can have a Story of Books or a Story of Text.
Warning: Java Generics tend to fall flat on their face when trying to complex things. In case of doubt, just forget generics and cast.
Thanks to all the posters. Here is my work-in-progress solution:
public abstract class Element
{
public ElementSet getContent() { return content; }
// Overrides of setContent() check to see if the content type is appropriate
// using instanceof.
public void setContent( ElementSet content )
{
this.content = content;
}
private ElementSet content;
}
public abstract class ElementSet
{
protected final void addElement( Element e )
{
elements.add(e);
}
private final List<Element> elements = new ArrayList<Element>();
}
public class BookSet extends ElementSet
{
// Typesafe interface.
public void addBook( Book book ) { super.addElement( book ); }
}
public class ChapterSet extends ElementSet { /* similar to BookSet */ }
public class SectionSet extends ElementSet { /* similar to BookSet */ }
public class Book extends Element
{
#Override
public void setContent( ElementSet content )
{
if ( !(content instanceof ChapterSet) && !(content instanceof SectionSet) )
{
throw new RuntimeException();
}
super.setContent( content );
}
public boolean addChapter( Chapter chapter )
{
ElementSet content = getContent();
if ( content == null )
{
content = new ChapterSet();
setContent( content );
}
else if ( !(content instanceof ChapterSet) )
{
// Structure is wrong.
return false;
}
ChapterSet chapters = (ChapterSet)content;
chapters.addChapter( chapter);
return true;
}
public boolean addSection( Section section )
{
ElementSet content = getContent();
if ( content == null )
{
content = new SectionSet();
super.setContent( content );
}
else if ( !(content instanceof SectionSet) )
{
// Structure is wrong.
return false;
}
SectionSet sections = (SectionSet)content;
sections.addSection( section );
return true;
}
}
public class Chapter extends Element
{
#Override
public void setContent( ElementSet content )
{
if ( !(content instanceof SectionSet) )
{
throw new RuntimeException();
}
super.setContent( content );
}
public boolean addSection( Section section )
{
ElementSet content = getContent();
if ( content == null )
{
content = new SectionSet();
super.setContent( content );
}
else if ( !(content instanceof SectionSet) )
{
// Structure is wrong.
return false;
}
SectionSet sections = (SectionSet)content;
sections.addSection( section );
return true;
}
}
I tried using generics to achieve the same end, but it looked rather ugly due to need to reflect the parametrised type of a container.
I am trying to use Ninject to implement cascading injection into a class that contains an IList field. It seems that, unless I specifically specify each binding to use in the kernel.Get method, the IList property is always injected with a list of a single default object.
The following VSTest code illustrates the problem. The first test fails because the IList field contains one MyType object with Name=null. The second test passes, but I had to specifically tell Ninject what constructor arguments to use. I am using the latest build from the ninject.web.mvc project for MVC 3.
Does Ninject specifically treat IList different, or is there a better way to handle this? Note that this seems to only be a problem when using an IList. Createing a custom collection object that wraps IList works as expected in the first test.
[TestClass()]
public class NinjectTest
{
[TestMethod()]
public void ListTest_Fails_NameNullAndCountIncorrect()
{
var kernel = new Ninject.StandardKernel(new MyNinjectModule());
var target = kernel.Get<MyModel>();
var actual = target.GetList();
// Fails. Returned value is set to a list of a single object equal to default(MyType)
Assert.AreEqual(2, actual.Count());
// Fails because MyType object is initialized with a null "Name" property
Assert.AreEqual("Fred", actual.First().Name);
}
[TestMethod()]
public void ListTest_Passes_SeemsLikeUnnecessaryConfiguration()
{
var kernel = new Ninject.StandardKernel(new MyNinjectModule());
var target = kernel.Get<MyModel>(new ConstructorArgument("myGenericObject", kernel.Get<IGenericObject<MyType>>(new ConstructorArgument("myList", kernel.Get<IList<MyType>>()))));
var actual = target.GetList();
Assert.AreEqual(2, actual.Count());
Assert.AreEqual("Fred", actual.First().Name);
}
}
public class MyNinjectModule : NinjectModule
{
public override void Load()
{
Bind<IList<MyType>>().ToConstant(new List<MyType> { new MyType { Name = "Fred" }, new MyType { Name = "Bob" } });
Bind<IGenericObject<MyType>>().To<StubObject<MyType>>();
}
}
public class MyModel
{
private IGenericObject<MyType> myGenericObject;
public MyModel(IGenericObject<MyType> myGenericObject)
{
this.myGenericObject = myGenericObject;
}
public IEnumerable<MyType> GetList()
{
return myGenericObject.GetList();
}
}
public interface IGenericObject<T>
{
IList<T> GetList();
}
public class StubObject<T> : IGenericObject<T>
{
private IList<T> _myList;
public StubObject(IList<T> myList)
{
_myList = myList;
}
public IList<T> GetList()
{
return _myList;
}
}
public class MyType
{
public String Name { get; set; }
}
lists, collections and arrays are handled slightly different. For those types ninject will inject a list or array containing an instance of all bindings for the generic type. In your case the implementation type is a class which is aoutobound by default. So the list will contain one instance of that class. If you add an interface to that class and use this one the list will be empty.