使用PrinterSettings.StringCollection时未设置对象引用

时间:2015-10-22 00:39:38

标签: c# object reference

我正在尝试使用PrinterSettings.StringCollection列出当前安装的打印机。但是,我收到了这个错误:

  

对象引用未设置为对象的实例

代码如下:

namespace DropDownLibrary
{
    public class DropDownExample : DSDropDownBase
    {
        public DropDownExample() : base("item") { }

        public static PrinterSettings.StringCollection InstalledPrinters { get; }

        public override void PopulateItems()
        {
            // The Items collection contains the elements
            // that appear in the list.            

            Items.Clear();

            // Create a number of DynamoDropDownItem objects 
            // to store the items that we want to appear in our list.

            var newItems = new List<DynamoDropDownItem>();
            {
                 foreach (String name in InstalledPrinters)
                 {
                     new DynamoDropDownItem("{0}", name);
                 }
            };

            Items.AddRange(newItems);

            // Set the selected index to something other
            // than -1, the default, so that your list
            // has a pre-selection.

            SelectedIndex = 0;
        }

        public override IEnumerable<AssociativeNode> BuildOutputAst(List<AssociativeNode> inputAstNodes)
        {
            // Build an AST node for the type of object contained in your Items collection.

            var intNode = AstFactory.BuildIntNode((int)Items[SelectedIndex].Item);
            var assign = AstFactory.BuildAssignment(GetAstIdentifierForOutputIndex(0), intNode);

            return new List<AssociativeNode> { assign };
        }
    }
}

1 个答案:

答案 0 :(得分:1)

this post中介绍了这一点。 “对象引用未设置为对象的实例”错误是由于您尝试使用null变量引起的。例如,您可以通过执行以下操作来获取空引用错误:

object nullObject = null;
nullObject.ToString():

在您的代码中,InstalledPrinters的值似乎不会被设置。

在您的代码到达此行之前:

foreach (String name in InstalledPrinters)

看起来你是从this link复制粘贴的:

public static PrinterSettings.StringCollection InstalledPrinters { get; }

这是您可以访问的PrinterSettings类的属性。您应该像这样访问它:

var installedPrinters = System.Drawing.Printing.PrinterSettings.InstalledPrinters;

foreach (String name in installedPrinters)