验证 C# 构造函数对象 null 处置
我是 C# 中面向对象编程的新手。所以请耐心等待。 如果 this.OrderCost() 大于 10000.00,我不想创建对象。如何删除此对象。在这里进行验证是否正确。什么是最好的方法。
public Bank(string bankCode, string bankName)
{
this.bankCode= bankCode;
this.bankName= bankName;
if (this.orderCost() > moneyInBankAccount)
{
MessageBox.Show("Order amount exceeds the money in bank account.");
this. = null; // <--what to do here.
}
}
I am new to object oriented prog in c#.So kindly bear me.
I dont want to create object, if this.OrderCost() is more than 10000.00.How to drop this object. Is it correct to do validtion here. What is the best possible way.
public Bank(string bankCode, string bankName)
{
this.bankCode= bankCode;
this.bankName= bankName;
if (this.orderCost() > moneyInBankAccount)
{
MessageBox.Show("Order amount exceeds the money in bank account.");
this. = null; // <--what to do here.
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
不应在对象的构造函数中完成此类型的验证。相反,它应该在执行您想要执行的操作的方法中完成。
因此,如果您尝试从银行帐户中扣除资金来支付订单,您将在“提款”方法中执行验证。
Validation of this type shouldn't been done in the constructor of the object. Instead it should be done in the method that is performing the action you intend to perform.
So, if you are attempting to deduct the money from the bank account to pay for an order you would perform the validation in the "Withdraw" method.
除了在这里不适用的几种非常罕见的情况外,如果构造函数返回,它要么返回构造的对象,要么抛出异常。
因此,为了避免构造无效的对象,您应该抛出异常。或者,您可以创建一个返回
null
的方法(如果对象无效),否则创建它。另外,您不应该处理域对象中的 UI,因此不要在那里显示该消息框。
Except in several very rare circumstances that are not applicable here, if a constructor returns, it either returns the constructed object or it throws an exception.
So, to avoid construction of an object that would be invalid, you should throw an exception. Or you could create a method that returns
null
is the object would be invalid and create it otherwise.Also, you shouldn't deal with the UI in the domain objects, so don't show that message box there.
不可能“分配”给它或以其他方式阻止构造函数完成其工作。您可以抛出异常或以其他方式指示新创建的对象无效。
编辑
您还可以创建一个静态方法,如果满足您的条件,该方法将返回 Bank 对象,否则返回 null。
It is not possible to "assign" to this or somehow else prevent the constructor from doing its job. You can either throw exception or somehow else indicate, that the newly created object is invalid.
EDIT
You can also create a static method, that will return a Bank object if your conditions are met, or return null otherwise.
与其他答案相比,这没什么新鲜的。只是为了展示你如何做到这一点。
或者
如果您不相信,请尝试阅读测试类的“I”
Here is nothing new than other answers. Just to show how you can do it.
or
If you are not convinced try to read the "I" of test class