با عرض سلام و وقت بخیر خدمت کاربران سایت پی وی لرن ، با یکی دیگر از جلسات دوره کامل آموزش #C در خدمت شما دوستان هستیم . در بخش قبلی با Extension methods ها در زبان #C آشنا شدید ، در این بخش قصد داریم شما را با انواع ناشناس در #C یا Anonymous Type در #C آشنا کنیم. تا پایان این جلسه همراه ما باشید.
1 2 3 4 5 6 7 | static void Main(string[] args) { var myAnonymousType = new { firstProperty = "First", secondProperty = 2, thirdProperty = true }; } |
یک نوع ناشناس می تواند یک نوع ناشناس دیگر را به عنوان یک پراپرتی داشته باشد.
1 2 3 4 5 6 7 | var myAnonymousType = new { firstProperty = "First", secondProperty = 2, thirdProperty = true, anotherAnonymousType = new { nestedProperty = "Nested"} }; |
anonymous types های تودرتو نیز دارای اینتلیسنس (intellisense) (سامانه هوشمند تکمیل کد مایکروسافت) هستند.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 | static void Main(string[] args) { var myAnonymousType = new { firstProperty = "First Property", secondProperty = 2, thirdProperty = true }; DoSomethig(myAnonymousType); } static void DoSomethig(dynamic param) { Console.WriteLine(param.firstProperty); } |
1 | First Property |
کد select در Linq یک anonymous type را ایجاد می کند که نتیجه پرس و جو شامل پراپرتی های مختلفی است که هیچ یک در کلاس تعریف نشده اند.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | public class Student { public int StudentID { get; set; } public string StudentName { get; set; } public int age { get; set; } } class Program { static void Main(string[] args) { IList<Student> studentList = new List<Student>() { new Student() { StudentID = 1, StudentName = "John", age = 18 } , new Student() { StudentID = 2, StudentName = "Steve", age = 21 } , new Student() { StudentID = 3, StudentName = "Bill", age = 18 } , new Student() { StudentID = 4, StudentName = "Ram" , age = 20 } , new Student() { StudentID = 5, StudentName = "Ron" , age = 21 } }; var studentNames = from s in studentList select new { StudentID = s.StudentID, StudentName = s.StudentName }; } |
در مثال بالا، کلاس Student شامل پراپرتی های مختلفی است. در متد Main ، دستور select در linq نوع ناشناسی (anonymous type ) را ایجاد می کند که شامل StudentId و StudentName است .
در این بخش با انواع ناشناس (anonymous type) در زبان #C آشنا شدید ، در قسمت بعدی این آموزش قصد داریم به معرفی Dynamic Type ها در این زبان بپردازیم.