Mình có một class model, đại diện cho 1 entity 1 table trong database, và cần chuyển nó về 1 class DTO để response cho client. Thường thì sẽ định nghĩa method ToDto để convert hoặc xài automapper. Nhưng hôm nay mình có 1 cách khác, đó là xài toán tử explicit.
Ví dụ:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 namespace ConsoleApp ;public class StudentDto { public string Name { get ; set ; } public int Age { get ; set ; } public override string ToString () { return $"Name: {Name} , Age: {Age} " ; } } public class StudentModel { public string FirstName { get ; set ; } public string LastName { get ; set ; } public int YOB { get ; set ; } public static explicit operator StudentDto (StudentModel model ) { return new StudentDto { Age = DateTime.Now.Year - model.YOB, Name = $"{model.FirstName} {model.LastName} " }; } } public class Program { static void Main (string [] args ) { var studentModel = new StudentModel { YOB = 2000 , FirstName = "Nguyen" , LastName = "Van A" }; var studentDto2 = (StudentDto)studentModel; Console.WriteLine(studentDto2); } }