当前位置:主页 > 软件编程 > .NET代码 >

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

时间:2022-05-14 10:00:46 | 栏目:.NET代码 | 点击:

声明空构造函数可阻止自动生成默认构造函数。注意,如果您不对构造函数使用访问修饰符,则在默认情况下它仍为私有构造函数。但是,通常显式地使用 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();
}
}

您可能感兴趣的文章:

相关文章