PDA

View Full Version : ويژگيهاي سي شارپ 6.0



elec60
دوشنبه 07 مهر 1393, 12:09 عصر
$ Sign

هدف از $ ساده تركردن دسترسي به عناصر رشته است:


var col = new Dictionary<string, string>()
{
// using inside the intializer
$first = "Hashem"
};

//Assign value to member

//the old way:
col["first"] = "Hashem";

// the new way
col.$first = "Hashem";






Exception Filters

اين ويژگي در VB وجود داشت و هم اكنون به سي شارپ هم اضافه شده است. اين ويژگي امكان آن را فراهم مي كند كه بلوك catch شرطي داشته باشيم:


try { throw new Exception("Me"); } catch (Exception ex) if (ex.Message == "You") { // this one will not execute. } catch (Exception ex) if (ex.Message == "Me") { // this one will execute }







await in catch and finally block

معلوم نيست چرا مايكروسافت اين ويژگي رو با معرفي await و async در C#‎‎‎ 5.0 اضافه نكرده بود!
اگر بخواهيم از جزئيات خطا در بلوك catch لاگ بگيريم و در فايل ذخيره كنيم اين كار مستلزم انجام عمليات I/O خواهد بود و براي I/O Bound Operation بهتره از روشهاي آسنكرون استفاده كنيم:



try { DoSomething(); } catch (Exception) { await LogService.LogAsync(ex); }

elec60
دوشنبه 07 مهر 1393, 12:12 عصر
Declaration expressions

با اين ويژگي ميشه متغيير محلي رو داخل expression تعريف كرد:
كد قديم:


long id;if (!long.TryParse(Request.QureyString["Id"], out id)){ }




كد جديد:


if (!long.TryParse(Request.QureyString["Id"], outlong id)){ }





كه scoping rules مثل سابق هست.



using Static

ديگه براي دسترسي به Type هاي كلاس استاتيك نيازي به استفاده از نام كلاس نيست و فقط در using directives معرفي ميشه:


using System.Console; namespace ConsoleApplication10{ class Program { static void Main(string[] args) { //Use writeLine method of Console class //Without specifying the class name WriteLine("Hellow World"); } }
}




Auto property initialize

مقداردهي اوليه پراپرتي همانند فيلد شده. بايد دقت كرد كه در اين حالت setter داخلي اجرا نميشه و مقدار مستقيم تو فيلد متناظري كه كامپايلر ميسازه ذخيره ميشه:


public class Person { // You can use this feature on both //getter only and setter / getter only properties public string FirstName { get; set; } = "Hashem"; public string LastName { get; } = "Mousavi"; }





Primary Constructor

در شروع تعريف كلاس ميتوان سازنده را قرار داد. وقتي سازنده ديگري ايجاد شود بايد Primary Constructo توسط this() صدا زده شود:


//this is the primary constructor: class Person(string firstName, string lastName) { public string FirstName { get; set; } = firstName; public string LastName { get; } = lastName; }





Dictionary Initializer





// the old way of initializing a dictionary Dictionary<string, string> oldWay = new Dictionary<string, string>() { { "Afghanistan", "Kabul" }, { "United States", "Washington" }, { "Some Country", "Some Capital city" } }; // new way of initializing a dictionary Dictionary<string, string> newWay = new Dictionary<string, string>() { // Look at this! ["Afghanistan"] = "Kabul", ["Iran"] = "Tehran", ["India"] = "Delhi" };