简体   繁体   中英

Generic collection of MenuItems in C#?

I am working on displaying a list of audio input devices in the menu, and I'm fairly new to C#. The number of input devices not only varies from machine to machine, it is possible that someone might add or subtract a USB device while the program is running. I wrote code that checks whenever the menu is activated, but I have to limit the number of possible input devices. It's not likely that there will be more than 10 input devices, but, in order to understand C# better, I'd like to see if it's possible to use a generic so that I don't have to limit the list.

Here's what I have going for code now:

MainMenu sgFileMenu = new MainMenu(); 
List<MenuItem> inputDevice = new List<MenuItem>();

MenuItem myMenuItemInput = new MenuItem("&Input Devices");
sgFileMenu.MenuItems.Add(myMenuItemInput);

for (int i = 0; i < deviceCount; i++)
{
    myMenuItemInput.MenuItems.Add(inputDevice[i]);
}

That compiles but gives an ArgumentOutOfRange exception when I run it. I'm obviously missing something about how generics are set up- can somebody clue me in?

Added after reading some of the comments- deviceCount is an integer and is not 0- that's checked someplace else. It seems clear that I need to do something before:

    myMenuItemInput.MenuItems.Add(inputDevice[i]);

But I'm not sure what that is.

Try this:

for (int i = 0; i < inputDevice.Count; i++)
{
    myMenuItemInput.MenuItems.Add(inputDevice[i]);
}

Anyway, you've initialized inputDevice as an empty list, so it doesn't contain any MenuItem .

This has nothing to do with generics. I'm guessing deviceCount is some number other than 0. Since you initialize inputDevice but never actually add anything to it, it stays empty, and inputDevice[i] will throw that exception.

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