对象创建的限制 [英] Restriction of object Creation
本文介绍了对象创建的限制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Hi Team,
我想限制用户创建多个对象。我在单身概念中知道这个概念。但是我试图通过以下方式实现。
如果你观察下面的程序我在if循环中抛出异常如果我不抛出异常创建If循环对象,我将能够使用第三个对象访问该方法,即ex3.Display();有人可以帮助我如何处理异常,同时对象不会被创建
使用系统;
使用 System.Collections.Generic;
使用 System.Linq;
使用 System.Text;
命名空间 ObjectCreation
{
class ExampleClass
{
public static int classCount = 0 ;
public ExampleClass()
{
classCount ++;
if (classCount > 2 )
{
throw new 异常( 对象创建失败 - 对象创建仅限于一个);
}
else
{
Console.WriteLine( Object Created + classCount);
}
}
public void 显示( )
{
Console.WriteLine( 对象创建);
}
}
class 计划
{
静态 void Main( string [] args)
{
ExampleClass ex1 = new ExampleClass();
ExampleClass ex2 = new ExampleClass();
ExampleClass ex3 = new ExampleClass();
ex3.Display();
}
}
}
解决方案
请参阅我对该问题的评论。别担心:模式有很多不好的实现。它通常是微不足道的,但需要考虑一些需要全面考虑的微妙时刻。想看一个好的?这里: http://csharpindepth.com/Articles/General/Singleton.aspx [ ^ ]。
-SA
Hi Team,
I want to restrict user from creating more than 1 object . I know this concept in singleton concept. However I am trying to achieve in the following way.
If you observe the below program i am throwing exception inside the "if loop" if i dont throw the exception inside the "If" loop object gets created and i will be able to access the method using the third object i.e ex3.Display(); Can some one help me how to handle the exception at same time object does not get created
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
namespace ObjectCreation
{
class ExampleClass
{
public static int classCount = 0;
public ExampleClass()
{
classCount++;
if (classCount > 2)
{
throw new Exception("Object creation failed - object creation limited only for one");
}
else
{
Console.WriteLine("Object Created" + classCount);
}
}
public void Display()
{
Console.WriteLine("object created");
}
}
class Program
{
static void Main(string[] args)
{
ExampleClass ex1 = new ExampleClass();
ExampleClass ex2 = new ExampleClass();
ExampleClass ex3 = new ExampleClass();
ex3.Display();
}
}
}
解决方案
Please see my comment to the question. Don't worry: there are many bad implementations of the pattern. It's generally trivial, but there are some delicate moments to take into account which require thorough considerations. Want to see a good one? Here: http://csharpindepth.com/Articles/General/Singleton.aspx[^].
—SA
这篇关于对象创建的限制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文