【问题标题】:Error cannot declare instance members in a static class错误不能在静态类中声明实例成员
【发布时间】:2014-01-08 07:44:36
【问题描述】:
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];
        }
    }
}

【问题讨论】:

标签: c# asp.net .net


【解决方案1】:

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

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

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

  • 仅包含静态成员。

  • 无法实例化。

  • 已密封。

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

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

【讨论】:

    【解决方案2】:

    不能在静态类中声明实例成员

    这个错误的原因是因为-

    静态类应该只包含静态成员

    【讨论】:

    • 该类没有任何成员。只是一个静态函数。返回的静态函数可以有非静态成员。
    • @Eisenhorn 啊..你是对的,我没有检查代码就直接回答了。
    猜你喜欢
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 2014-03-19
    • 2018-05-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多