Skip to main content
 首页 » 编程设计

c#之以为我了解静态类

2024年02月24日11itcoder

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

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

我想我明白为什么您不想在每次调用此方法时都创建一个新的 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; 
    } 
 
} 

请您参考如下方法:

此处错误:

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

意味着您已经在方法的外部声明了 oDocument。

您发布的代码没有任何问题,实际上错误和代码相互矛盾。

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

public static class Util 
{ 
    static XmlDocument oDocument; 
 
    /* code */ 
}