Skip to main content
 首页 » 编程设计

c#之报错不能在静态类中声明实例成员

2024年02月13日13shangdawei

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Collections.Specialized; 
using System.Configuration; 

我收到这个错误

cannot declare instance members in a static class 

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

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

请您参考如下方法:

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

来自 Static Classes and Static Class Members (C# Programming Guide)

The following list provides the main features of a static class:

  • Contains only static members.

  • Cannot be instantiated.

  • Is sealed.

  • Cannot contain Instance Constructors.

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