C#私有构造函数使用方法 C#私有构造函数使用示例

软件发布|下载排行|最新软件

当前位置:首页IT学院IT技术

C#私有构造函数使用方法 C#私有构造函数使用示例

  2021-03-19 我要评论
想了解C#私有构造函数使用示例的相关内容吗,在本文为您仔细讲解C#私有构造函数使用方法的相关知识和一些Code实例,欢迎阅读和指正,我们先划重点:私有构造函数,下面大家一起来学习吧。

声明空构造函数可阻止自动生成默认构造函数。注意,如果您不对构造函数使用访问修饰符,则在默认情况下它仍为私有构造函数。但是,通常显式地使用 private 修饰符来清楚地表明该类不能被实例化。

示例代码:

复制代码 代码如下:

public class PrivateConClass
{
private static PrivateConClass pcc;

private PrivateConClass()
{
Console.WriteLine("This private constructure function. So you cannot create an instance of this class.");
}

public static PrivateConClass CreatePcc()
{
pcc = new PrivateConClass();
return pcc;
}

public static void ShowStaticMethod()
{
Console.WriteLine("This is a static method. Just be called by Class name.");
}

public void ShowMethod()
{
Console.WriteLine("This is a Nonstatic method. Just be called by private static instance pcc.");
}
}
class Program
{
static void Main(string[] args)
{
PrivateConClass pcc = PrivateConClass.CreatePcc();
pcc.ShowMethod();
PrivateConClass.ShowStaticMethod();
}
}

Copyright 2022 版权所有 软件发布 访问手机版

声明:所有软件和文章来自软件开发商或者作者 如有异议 请与本站联系 联系我们