C#类无法实例化10次以上 [英] C# class that can't be instantiated more than 10 times

查看:113
本文介绍了C#类无法实例化10次以上的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述




我班上有静态变量。

我使用get和set属性。

我喜欢以下。


这个问题有意义吗?


我的问题是main()中的对象调用。请帮帮我。

Hi,

I have static variable in my class.
I use get and set properties.
I do like below.

Does it make sense for this question?

My problem is object call in main(). Please help me out.

展开 | 选择 | Wrap | 行号

推荐答案

角度,


欢迎来到字节。

听起来你对C#还是比较陌生的我很想知道你是否理解了构造函数的概念?


构造函数(在C#中)是一个与类同名的方法,没有返回类型,因为它用于实例化。班级。在创建类的实例时调用它。构造函数的工作是确保实例化所有类成员(类变量)(使用new关键字)以便可以使用它们。


如果您的要求是创建一个只能实例化10次的类,那么您需要在构造函数中放置逻辑以满足此要求,因为在创建类的实例(实例化)时调用构造函数。



现在你有了名字中的逻辑。属性...但它不属于那里。


创建一个构造函数并将逻辑从Name属性移到构造函数中。


我还建议当有人试图实例化10个以上的类时抛出异常。


-Frinny
Angle,

Welcome to Bytes.
It sounds like you''re fairly new to C# and I was wonder if you understood the concept of a Constructor?

A Constructor (in C#) is a method that has the same name as the class, and no return type because it is used to "instantiate" the class. It is called when the an instance of the class is being created. It is the constructor''s job to ensure that all of the class members (class variables) are instantiated (using the "new" keyword) so that they can be used.

If your requirement is to create a class that can only be instantiated 10 times then you need to put the logic to fulfill this requirement in the constructor since the constructor is called when an instance of the class is created (instantiated).


Right now you have the logic in the "Name" property... But it doesn''t belong there.

Create a constructor and move the logic out of the Name property into the constructor.

I also recommend that you throw an Exception when someone attempts to instantiate more than 10 classes.

-Frinny




感谢Frinny。我回信但它有意义吗?
Hi ,
Thank Frinny. I write back but Does it make sense?
展开 | 选择 | Wrap | 行号


:)


它比上一个员工更有意义你发布的课程。我不会在你的构造函数中添加try / catch。


让异常被抛出到父/调用代码,以便它可以捕获异常。抛出异常是因为存在问题(已存在10个实例且您不能再创建)...所以由父/调用代码来处理问题。

-Frinny
:)

Well it makes more sense than the last Employee class you posted. I wouldn''t put a try/catch in your constructor though.

Let the Exception get thrown to the parent/calling code so that it can catch the Exception. The Exception is thrown because there was a problem (10 instances already exist and you can''t create any more)...so it is up to the parent/calling code to deal with the problem.

-Frinny


这篇关于C#类无法实例化10次以上的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆