错误无法在静态类中声明实例成员

Gib*_*boK 2 .net c# asp.net

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Collections.Specialized;
using System.Configuration;
Run Code Online (Sandbox Code Playgroud)

我收到此错误

cannot declare instance members in a static class
Run Code Online (Sandbox Code Playgroud)

在编写静态类时。如果可能的话,知道如何解决它保持类静态吗?谢谢

namespace XXX.Helpers
{
    public static class Utility
    {
        public static string GetConfiguration(string section, string key)
        {
            NameValueCollection mySection = (NameValueCollection)ConfigurationManager.GetSection(section);

            return mySection[key];
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

Son*_*nül 6

您不能在static类中定义非静态成员。在静态类中声明实例成员是不合法的。

从 Static Classes and Static Class Members (C# Programming Guide)

以下列表提供了静态类的主要功能:

  • 仅包含静态成员。

  • 无法实例化。

  • 是密封的。

  • 不能包含实例构造函数。

我不得不说,顺便说一下,我在你的静态类中没有看到任何实例成员 :)