【问题标题】:Thought I understood static classes以为我理解静态类
【发布时间】:2010-12-21 08:22:10
【问题描述】:

试图构造一个返回数组列表的辅助类,但我收到以下错误,这与我需要创建的 xml 文档有关:

Util.oDocument':不能在静态类中声明实例成员

我想我理解为什么您不想在每次调用此方法时都创建一个新的 xmldoc 对象,但我需要该文档以实现该功能。我应该如何处理这个?

using System;
using System.Collections;
using System.Xml;

public static class Util
{

    public static ArrayList multipleArtistList(string artistName)
    {
        XmlDocument oDocument = new XmlDocument();

        string uri = "http://api.leoslyrics.com/api_search.php?auth=duane&artist=" + artistName;
        oDocument.Load(uri);

        XmlNodeList results = oDocument.GetElementsByTagName("name");
        ArrayList artistList = new ArrayList();

        for (int i = 0; i < results.Count; i++)
        {
            if (!artistList.Contains(results[i].InnerText))
            {
                artistList.Add(results[i].InnerText);

            }

        }

        return artistList;
    }

}

【问题讨论】:

  • 你/确定/ oDocument 是在方法内部声明的,还是一个字段?
  • 我看不出该代码有什么问题。如果 oDocument 的声明在任何函数之外,您应该只会收到该错误。
  • 之前的 cmets 似乎是正确的。否则,您也无法声明您正在使用的任何其他变量。
  • 刚刚尝试在 MonoDevelop 中编译该代码,没有任何错误。暂时无法访问 VS。

标签: c# oop static


【解决方案1】:

这里出现这个错误:

Util.oDocument: cannot declare instance members in a static class

表示您已在方法外部声明了oDocument。

你贴的代码没有问题,实际上错误和代码相互矛盾。

确保在方法内部声明了oDocument。如果您想将其声明为字段,请确保为其提供 static 修饰符,如下所示:

public static class Util
{
    static XmlDocument oDocument;

    /* code */
}

【讨论】:

  • 酷,谢谢。又试了一次,很好。很高兴知道我在正确的轨道上。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-18
相关资源
最近更新 更多