开发者

Cannot declare instance members in a static class in C#

I have a public static class and I am trying to access appSettings from my app.config file in C# and I get the error described in the title.

开发者_StackOverflow社区
public static class employee
{
    NameValueCollection appSetting = ConfigurationManager.AppSettings;    
}

How do I get this to work?


If the class is declared static, all of the members must be static too.

static NameValueCollection appSetting = ConfigurationManager.AppSettings;

Are you sure you want your employee class to be static? You almost certainly don't want that behaviour. You'd probably be better off removing the static constraint from the class and the members.


It says what it means:

make your class non-static:

public class employee
{
  NameValueCollection appSetting = ConfigurationManager.AppSettings;    
}

or the member static:

public static class employee
{
  static NameValueCollection appSetting = ConfigurationManager.AppSettings;    
}


It is not legal to declare an instance member in a static class. Static class's cannot be instantiated hence it makes no sense to have an instance members (they'd never be accessible).


I know this post is old but...

I was able to do this, my problem was that I forgot to make my property static.

public static class MyStaticClass
{
    private static NonStaticObject _myObject = new NonStaticObject();

    //property
    public static NonStaticObject MyObject
    {
        get { return _myObject; }
        set { _myObject = value; }
    }
}


Have you tried using the 'static' storage class similar to?:

public static class employee
{
    static NameValueCollection appSetting = ConfigurationManager.AppSettings;    
}


As John Weldon said all members must be static in a static class. Try

public static class employee
{
     static NameValueCollection appSetting = ConfigurationManager.AppSettings;    

}


public static class Employee
{
    public static string SomeSetting
    {
        get 
        {
            return ConfigurationManager.AppSettings["SomeSetting"];    
        }
    }
}

Declare the property as static, as well. Also, Don't bother storing a private reference to ConfigurationManager.AppSettings. ConfigurationManager is already a static class.

If you feel that you must store a reference to appsettings, try

public static class Employee
{
    private static NameValueCollection _appSettings=ConfigurationManager.AppSettings;

    public static NameValueCollection AppSettings { get { return _appSettings; } }

}

It's good form to always give an explicit access specifier (private, public, etc) even though the default is private.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜