开发者

Is static variable shared between class instances

开发者 https://www.devze.com 2023-04-01 07:34 出处:网络
I have the class below. _commandLine variable is declared as static. Does this variable will be shared between WkHtml class instances?

I have the class below. _commandLine variable is declared as static. Does this variable will be shared between WkHtml class instances?

p.s. It would be cool to have Tool which would show such information in VS. For example developer select variable and get information about variable, is variable shared between classes, is it thread safe and etc.

public class WkHtml
{
    private static string _commandLine;

    public void AddCommandLine(object value)
    {
        AddCommandLine("{0}", value);
    }

    public void AddCmdWithCond(string value, bool condition, object compareValue)
    {
        AddCmdWithCond(value, condition, compareValue, "");
    }

    public void AddCmdWithCond(string value, bool condition, object compareValue, string defaultValue开发者_JAVA技巧)
    {
        if (compareValue != null && !string.IsNullOrEmpty(compareValue.ToString()) && Helpers.GetBool(compareValue) == condition)
            AddCommandLine("{0}", value);
        else
            if (defaultValue != null)
                AddCommandLine("{0}", defaultValue);
    }

    public void AddCommandLine(object parameter, object value, object defaultValue)
    {
        if (value == null || string.IsNullOrEmpty(value.ToString()))
        {
            value = defaultValue;
        }
        AddCommandLine(parameter, value);
    }

    public void AddCommandLine(object parameter, object value)
    {
        if (value == null || string.IsNullOrEmpty(value.ToString())) return;
        _commandLine = _commandLine + string.Format(parameter.ToString(), value) + " ";
    }

    public string GetCommandLine
    {
        get { return _commandLine; }
    }

}


static variables are shared between all class instances.

I don't see any reason to why you should declare it as static?


Does this variable will be shared between WkHtml class instances?

yes it does - and equally, it applies to none, but rather: the type itself. You can use a static variable without any instances of the type.

and get information about variable, is variable shared between classes

you already do - the S symbol in intellisense, and the static modifier.

is it thread safe

that is more complicated, and cannot be evaluated by such - it is impossible to comment on thread-safety without a deep understanding of the code and how it is used.


yes it is a class variable,all instances of the class will have see the same value of the property.if one instance changes it ,it will reflect for all the instances.


static variables are indeed "shared" between class instances, though it is instance independent. A static variable is part of the class, but not instances of that class.

0

精彩评论

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