软件编程
位置:首页>> 软件编程>> C#编程>> C#私有构造函数使用示例

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

  发布时间:2021-12-31 02:14:53 

标签:私有构造函数

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

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com