简体   繁体   中英

C# iterators and pointers?

I know there are no pointers in C#, but I am trying to figure out how to do the following, which I would have done with pointers (or better yet, iterators) in C++ (I am taking a course in C#, but I already know C++).

We got an assignment to write a simple "store" program (inventory, transactions, etc.). My first idea (coming from C++) was this: have a linked list of items and their amount in stock. Then, have a class representing a sale, which has a list of the items in the current sale, where each item is represented as an iterator to specific items in the master stock list and a value for the amount. (I hope this is clear.)

I tried to do the same in C# but can't figure out how to get those iterators to the master list (they should preferably also be good across updates to the master list). How do you do this?

You don't need to do anything special to use references, they are used by default in C#.

I'm assuming you'd do something like this in C++:

class Sale {
  public:
    void AddItem(Item* i) {
        items.push_back(i);
    }

  private:
    std::vector<Item*> items;
};

In C#, since it uses references rather than pass by value by default, you get that behavior by default. You'd get similar behavior in C# from the following code:

class Sale {
  private List<Item> items;

  public void AddItem(Item i) {
    items.Add(i);
  }
}

To call this C# code you could just do something like

Item item = new Item("A test item");
Sale sale = new Sale();
sale.AddItem(item);

You would almost certainly have to write your own iterator-style interface - C# doesn't seem to offer anything close to so flexible. You could write your own extension methods and a class that offers this, but you'd have to do it yourself, I'm fairly sure that it doesn't exist in the .NET standard libraries.

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