简体   繁体   中英

Removing items from collection class c#

I have a collection class with books. I have a remove method that i want to use, and that is after ive added the books. Here are my books:

myList<Book> lst = new myList<Book>();
        lst.addItem(new Book("Dumas", "Alexandre", "The Count Of Monte Cristo", 1844));
        lst.addItem(new Book ("Clark", "Arthur C",  "Rendezvous with Rama", 1972 ));
        lst.addItem(new Book("Dumas", "Alexandre", "The Three Musketeers", 1844)); ;
        lst.addItem((new Book ("Defoe",  "Daniel",  "Robinson Cruise",  1719)));
        lst.addItem(new Book ("Clark",  "Arthur C",  "2001: A space Odyssey",  1968 ));

My remove method looks like this:

public void removeItem(T item)
{
    Array.Resize(ref items, items.Count() -2);
}

So, if I want to remove for example the first book from the list, i tried to do :

lst.removeItem(0);

But i get an error saying that "No overload for method 'removeItem' takes 0 arguments"

What im I doing wrong?

But i get an error saying that "No overload for method 'removeItem' takes 0 arguments"

What im I doing wrong?

public void removeItem(T item) // <-- code within brackets is the "overload"
{
    Array.Resize(ref items, items.Count() -2);
}

As the constructor you've created for your method only accepts one argument, you can only utilize the method by passing a singular argument into it.

If it did accept "0 arguments" it would need a constructor that looks like this:

public void RemoveItem()
{
    // your code here
}

However as you need at least one argument to be passed into your method this isn't going to resolve your problem.

To be receiving the error "No overload for method 'removeItem' takes 0 arguments" you would have to call removeItem like this:

RemoveItem();

So I would suggest hitting CTRL+F and searching for RemoveItem(); to find where in your project it is.

This method you have made takes one argument of type "T" removeItem(T item)

So you should receive an error (unable to cast to type) message because you are passing an integer 0 into a method that doesn't accept Integers, it accepts your "T" type.

As many people have already stated in the comments, you should be using the List class provided by .NET for this. There is no point reinventing the wheel when Microsoft have already created and fine tuned it.

An additional tip, although this will not affect your code but the standard for naming methods is Pascal Case. So you should call it RemoveItem instead of removeItem

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM