我想防止使用Asp.net核心流利性验证更新属于对象的FirstName和LastName属性

问题描述

这是我输入的DTO:

 public class Individualinformation : IPerson
 {
     public string FirstName { get; set; }
     public string LastName { get; set; }
     public Address PrimaryAddress { get; set; }
     public DateTime? DateOfBirth { get; set; }
     public string CitizenShip { get; set; }
 }

用户尝试使用流利验证来更新名字和姓氏时,我想阻止它。

要做那件事我需要写什么规则?

解决方法

似乎您正在寻找不可变(只读)属性。这是一个示例:

 public class IndividualInformation : IPerson
 {
     public string FirstName { get; }
     public string LastName { get; }
     public Address PrimaryAddress { get; set; }
     public DateTime? DateOfBirth { get; set; }
     public string CitizenShip { get; set; }

    public IndividualInformation(string firstName,string lastName)
    {
        FirstName = firstName;
        LastName = lastName;
    }
 }

var info = new IndividualInformation("Jane","Doe")
{
    PrimaryAddress = ...
};

info.FirstName = "John"; // this will throw an error

如果启用了C#9,则可以为此使用init属性:

 public class IndividualInformation : IPerson
 {
     public string FirstName { get; init; }
     public string LastName { get; init; }
     public Address PrimaryAddress { get; set; }
     public DateTime? DateOfBirth { get; set; }
     public string CitizenShip { get; set; }
 }

var info = new IndividualInformation
{
    FirstName = "Jane",LastName = "Doe",PrimaryAddress = ...
};

info.FirstName = "John"; // this will throw an error

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...