静态问题 [英] static question

查看:76
本文介绍了静态问题的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

大家好

我知道,当一个对象是静态对象时,在任何给定时间只能存在一个对象.我也知道,如果一个类是静态的,我不需要实例化它就可以使用它,这是非常有用的:)

我不明白的是为什么在可实例化的类中包含静态变量有用吗?

示例:

Hey guys

I know that when an object is static only one of that object can exist at any given time. I also know that if a class is static I don''t need to instantiate it to use it which is very useful :)

What i don''t get is why is it useful to have a static variable inside of an instantiate-able class?

Example:

public class Foo
{
    public Foo(int Bar)
    {
        bar = Bar;
    }

    private static int bar;
    public static int Bar
    {
        get { return bar; }
        set { bar = value; }
    }
}



通常,如果您希望同一类型的多个对象共享数据,则请使用



Thanks

推荐答案

.例如,您可能有一个静态RootNode成员,如果您所有的对象都需要引用它-这样,您只需要为整个类初始化一次即可,而不是针对每个实例
Generally, if you want multiple objects of the same type to share data. For example, you might have a static RootNode member, if all your objects need to refer to it - that way you only need to initialise it once for the whole class, rather than per-instance


必须由该类的所有实例共享的所有信息(或不共享任何信息)都是不错的选择.
例如,如果您要计算该类创建了多少个实例(请原谅,双关语).
:)
Every info that has to be shared by all the instances (or none of them) of the class could be a good candidate.
For instance if you want to count how many instances (pardon the pun) of the class were created.
:)


另一个示例是Message类,其中每个实例都有一个唯一的ID,该ID是先前分配的ID + 1;
Another example is a Message class in which each instance has a unique ID that is the previously assigned ID + 1;


这篇关于静态问题的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆