类包含私有构造函数和公共属性,那么我们如何在C#中分配公共属性 [英] Class contains private constructor, and public property, then how can we assign the public property in C#

查看:83
本文介绍了类包含私有构造函数和公共属性,那么我们如何在C#中分配公共属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

公共课mUIPassword

{

public mUserPasswords user {get;组; }

公共字符串频道{get;组; }

public string lang {get;组; }

mUIPassword()

{

channel =device | Web;

lang =en ;

}

}

公共类mUserPasswords

{

public string newPassword {get;组; }

public string oldPassword {get;组; }

}



我的尝试:



这里我如何分配用户属性?

public class mUIPassword
{
public mUserPasswords user { get; set; }
public string channel { get; set; }
public string lang { get; set; }
mUIPassword()
{
channel = "device|Web";
lang = "en";
}
}
public class mUserPasswords
{
public string newPassword { get; set; }
public string oldPassword { get; set; }
}

What I have tried:

Here how can I assign user property?

推荐答案

当类需要保持对创建的实例的控制时,使用私有构造函数(通常作为一个Singleton类,其中只创建了一个类的实例)。

在这种情况下,类需要提供一个创建和返回实例的方法,或者非静态属性和方法根本无法访问(因为它们需要一个实例才能使用)。



因此在您的具体示例中,答案是您不能。

但是如果你提供上述方法,你可以:



Private constructors are used when the class needs to maintain control over the instances that are created (most often as a Singleton class where there is only ever one instance of the class created).
In those circumstances, the class needs to provide a method to create and return an instance, or the non-static properties and methods cannot be accessed at all (since they require an instance in order to be used).

So in your specific example, the answer is "you can't".
But you can if you provide a method as mentioned:

public class mUIPassword
    {
    public mUserPasswords user { get; set; }
    public string channel { get; set; }
    public string lang { get; set; }
    private mUIPassword()
        {
        channel = "device|Web";
        lang = "en";
        }
    private static mUIPassword theInstance = null;
    public static mUIPassword GetInstance()
        {
        if (theInstance == null) theInstance = new mUIPassword();
        return theInstance;
        }
    }


这篇关于类包含私有构造函数和公共属性,那么我们如何在C#中分配公共属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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