Friday, 1 November 2019
c# - Having a collection in class
Answer
Answer
There are several options when one class must have a container (collection) of some sort of objects and I was wondering what implementation I shall prefer.
Here follow the options I found:
public class AClass : IEnumerable{
private List values = new List()
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator GetEnumerator(){
return values.GetEnumerator();
}
}
Pros: AClass is not dependent on a concrete implementation of a collection (in this case List).
Cons: AClass doesn't have interface for Adding and removing elements
public class AClass : ICollection{
private List values = new List()
IEnumerator IEnumerable.GetEnumerator()
{
return GetEnumerator();
}
public IEnumerator GetEnumerator(){
return values.GetEnumerator();
}
//other ICollectionMembers
}
Pros: Same as IEnumerable plus it have interface for adding and removing elements
Cons: The ICollection interface define other methods that one rarely uses and it get's boring to implement those just for the sake of the interface. Also IEnumerable LINQ extensions takes care of some of those.
public class AClass : List{
}
Pros: No need of implementing any method. Caller may call any method implemented by List
Cons: AClass is dependent on collection List and if it changes some of the caller code may need to be changed. Also AClass can't inherit any other class.
The question is: Which one shall I prefer to state that my class contains a collection supporting both Add and Remove operations? Or other suggestions...
Answer
My suggestion is just define a generic List inside of your class and write additional Add
and Remove
methods like this and implement IEnumerable:
public class MyClass : IEnumerable
{
private List myList;
public MyClass()
{
myList = new List();
}
public void Add(string item)
{
if (item != null) myList.Add(item);
}
public void Remove(string item)
{
if (myList.IndexOf(item) > 0) myList.Remove(item);
}
public IEnumerable MyList { get { return myList; } }
public IEnumerator GetEnumerator()
{
return myList.GetEnumerator();
}
}
This is the best way if you don't want to implement your own collection.You don't need to implement an interface to Add
and Remove
methods.The additional methods like this fits your needs I guess.
php - file_get_contents shows unexpected output while reading a file
I want to output an inline jpg image as a base64 encoded string, however when I do this : $contents = file_get_contents($filename); print ...
-
I have an app which needs a login and a registration with SQLite. I have the database and a user can login and register. But i would like th...
-
I got an error in my Java program. I think this happens because of the constructor is not intialized properly. My Base class Program public ...
-
I would like to use enhanced REP MOVSB (ERMSB) to get a high bandwidth for a custom memcpy . ERMSB was introduced with the Ivy Bridge micro...
No comments:
Post a Comment