开发者

C# Adding to list issue

Hey guys, I have an application which consists of a baseclass (MacroCommand), three subclasses of MacroCommand (Resize, Rotate, Colour), and another class which does not inherit anything (Image) and then another class (Macro) which holds a list of MacroCommands

class Macro
{
    List<MacroCommand> macroCommandList = new List<MacroCommand>();
}

Basically, when I create my MacroCommand objects in the Form class, I need to then add them to the MacroCommand list, however, I keep getting errors when I try to do this:

macroCommandList.Add(colourObject);
macroCommandList.Add(rotateFlipObject);
macroCommandList.Add(resizeObject);

(this is in the Form class)

Any help would be appreciated, thanks guys.

EDIT: Errors:

Error 开发者_如何学Go2 The name 'colourObject' does not exist in the current context C:\Users\Ari\Desktop\Assignment 3\Assignment 3\Assignment 3\Form1.cs 134 42 Assignment 3 Error 3 The name 'macroCommandList' does not exist in the current context C:\Users\Ari\Desktop\Assignment 3\Assignment 3\Assignment 3\Form1.cs 135 21 Assignment 3

It's just these errors but for each different line


This should work:

class Macro {
    private List<MacroCommand> macroCommandList = new List<MacroCommand>();

    public void AddMacroCommand(MacroCommand mc)
    {
        macroCommandList.Add(mc);
    }
}


According to the error, the objects you're trying to add don't exist. Where are those objects declared? What is their scope? The list is private by default, so you need to supply those objects as arguments to the method which is adding them to the list.


If you have a List<BaseClass> you can only add to it elements that can be converted to the BaseClass (i.e. BaseClass'es and classes derived from BaseClass).

If you want to add elements to a list (say, macroCommandList ) you need to make sure the list is accesible to the calling code. This means either making it public (not a very good idea) or adding a public method to its containig class (i.e. Macro) that does the adding. The method is public so it is accessible to callers outside the class and it also has access to the private variable macroCommandList.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜