类包含私有构造函数和公共属性,那么我们如何在C#中分配公共属性

编程入门 行业动态 更新时间:2024-10-22 07:30:07
本文介绍了类包含私有构造函数和公共属性,那么我们如何在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#中分配公共属性

本文发布于:2023-11-14 00:09:08,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1585675.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:属性   函数   分配   如何在

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!