没有私有构造函数,我们可以从一个类到另一个类访问静态成员吗​​? [英] Without private constructor we can access static member from one to other class?

查看:143
本文介绍了没有私有构造函数,我们可以从一个类到另一个类访问静态成员吗​​?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用私有构造函数:它无法创建实例,它不能继承,它只包含静态数据成员



没有私有构造函数我也能够具有静态声明和静态数据成员的访问类在分配值时如下例所示



use of private constructor : it cant able to create instance, it cant be inherit, it contain only static data members

without private constructor also i can able to access class with its static declaration and static data member when assign value like the below example

class Test
{        
    public static int x = 12;
    public static int method()
    {
        return 13;
    }
}
class Program
{
    int resut1 = Test.x;
    int resut2 = Test.method();
    static void Main(string[] args)
    {
    }
}



所以我怀疑下面为什么要去私有构造函数是什么私有构造函数块的使用是我们不能在私有构造函数块中执行任何操作时请执行清楚说明



提前感谢



我尝试了什么:



i没有私人施工人员试过


私有构造函数中的
在非静态方法内部或类块内调用时也不会访问静态数据成员。



与一个类(class1)相同拥有静态数据成员和另一个类(class2)



class1静态数据成员无法在class2中调用


so i have doubts as below why should go to private constructor what is the use of private constructor block is we cant do anything inside of private constructor block when it execute please explain clearly

thanks in advance

What I have tried:

i tried without private constructor

in private constructor also not access static data members when call inside of non static methods or inside of class block.

the same as one class (class1 ) have static data members and another class (class2)

class1 static data member cant able to call in class2

推荐答案

私有构造函数只是阻止外部类创建任何i nstances - 它们主要用于Singleton类。但这对 static 项目完全没有影响,因为它们根本不需要实例。

所以这个:

Private constructors just prevent "outside" classes from creating any instances - they are mostly used for Singleton classes. But that has no effect at all on static items because they do not require an instance to work at all.
So this:
public MyClass
    {
    private MyClass() {}
    public static myProperty { get; set; }
    public static int myMethod( int x) { return x * 2; }
    public MyClass GetInstance() { return new MyClass(); }
    }

myProperty myMethod 外部代码都可以访问GetInstance


这篇关于没有私有构造函数,我们可以从一个类到另一个类访问静态成员吗​​?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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