[Obsolete("This func is obsolete, use newFunc()")] publicvoidOldFunc() { // do something }
数据验证
可以确保某个数据存在
publicclassUserModel { [Required(ErrorMessage = "Username is required.")] public string Username { get; set; }
[Required(ErrorMessage = "Password is required.")] public string Password { get; set; } }
// 创建一个对象,但是没有填充Required信息 var invalidUser = new UserModel(); var validationResults = new List<System.ComponentModel.DataAnnotations.ValidationResult>(); bool isValid = Validator.TryValidateObject(invalidUser, new ValidationContext(invalidUser), validationResults, true); if (!isValid) { string errorMessage = string.Empty; foreach (var validationResult in validationResults) { errorMessage +=validationResult.ErrorMessage; } // 输出 "Username is required.Password is required." Console.WriteLine(errorMessage); }
序列化与反序列化
WCF
Windows Communication Foundation
[DataContract] publicclassPerson { [DataMember] publicstring Name { get; set; }
[DataMember] publicint Age { get; set; } }
var person = new Person { Name = "John", Age = 20 }; var serializer = new DataContractSerializer(typeof(Person)); // 序列化 using (var memoryStream = new MemoryStream()) { serializer.WriteObject(memoryStream, person); memoryStream.Position = 0; var serializedData = new StreamReader(memoryStream).ReadToEnd(); LabelText = serializedData; } // 反序列化 using (var reader = XmlReader.Create(new StringReader(LabelText))) { var deserializedPerson = (Person)serializer.ReadObject(reader); }
[Serializable] publicclassPerson { publicstring Name { get; set; } publicint Age { get; set; } }
Person person = new Person { Name = "John Doe", Age = 30 };
// 序列化 Person 对象到文件 System.Xml.Serialization.XmlSerializer serializer = new System.Xml.Serialization.XmlSerializer(typeof(Person)); using (var stream = new System.IO.FileStream("F:\\person.xml", System.IO.FileMode.Create)) { serializer.Serialize(stream, person); }
// 反序列化从文件读取的数据 using (var stream = new System.IO.FileStream("F:\\person.xml", System.IO.FileMode.Open)) { Person deserializedPerson = (Person)serializer.Deserialize(stream); Console.WriteLine($"Name: {deserializedPerson.Name}, Age: {deserializedPerson.Age}"); }