因此,我刚刚开始一个新项目,并且对此非常陌生,但我的基本想法是:如果我有一个客户类:
public class Customer
{
public int id{ get; private set; }
public String firstName { get; private set; }
public DateTime age { get; private set; }
public String LastName { get; private set; }
public String address { get; private set; }
public String city { get; private set; }
public String emailAddress { get; private set; }
public Customer(String firstName, String LastName, String address, String city, String emailAddress, DateTime age)
{
this.firstName = firstName;
this.LastName = LastName;
this.address = address;
this.city = city;
this.age = age;
this.emailAddress = emailAddress;
}
并希望使用此验证器类来检查是否有合适的firstName。
public class Validator
{
public bool NameValidator(String user){
while (string.IsNullOrEmpty(user) || user.Length > 35)
{
Console.WriteLine("Name can't be empty! Input your name once more");
Console.ReadLine();
}
return true;
}
使用NameValidator方法的最佳方法是什么,以便当它是真的时候,它可以创建一个Customer对象?还是有更好的方法?
Customer newCustomer = new Customer(fname);
发布于 2021-04-15 18:11:08
我可以看到至少3个选项(加上混合和匹配):
System.ComponentModel.DataAnnotations
(向模型(C#)添加验证)进行验证你可以只是:
public Customer(String firstName, String LastName, String address, String city, String emailAddress, DateTime age)
{
if(string.IsNullOrEmpty(firstName) || firstName.Length > 35) {
throw new ArgumentException("Bad bad name!");
}
this.firstName = firstName;
this.LastName = LastName;
this.address = address;
this.city = city;
this.age = age;
this.emailAddress = emailAddress;
}
请注意,如果您曾经反序列化客户,您需要确保验证运行,但不一定在反序列化。您可能希望在之后运行它,以提供更好的错误处理。
发布于 2021-04-15 18:10:37
方法1
public class Validator
{
public bool NameValidator(String user){
if(string.IsNullOrEmpty(user) || user.Length > 35)
{
throw new Exception("user object is wrong!");
}
return true;
}
这将在验证失败后中断代码执行。
方法2
在setter方法中调用验证
public void setName(String name){
if(new Validator().validateName(name) == true){
this.name = name;
}
}
方法3
理想情况下,我们应该在调用业务逻辑之前进行验证。因此,只要从用户读取值并提示再次输入,就可以调用验证器方法。我要做的是先读取值,然后单独验证值,如果错误的话再次插入,最后处理值。
https://stackoverflow.com/questions/67117964
复制相似问题