Artigo Principal - As Novas Funcionalidades do C# 3.0 Article Home - The New Features of C # 3.0
Hoje vou falar-vos de outra funcionalidade introduzida com o C# 3.0 que são os Object Initializers , que permitem inicializar objectos, de uma forma mais compacta e rápida que o tradicional. Today I will speak to you of another feature introduced with the C # 3.0 that are the Object Initializers, allowing boot objects, more compact and fast that the traditional.
Com esta funcionalidade podemos inicializar as propriedades de um objecto logo na declaração do mesmo, utilizando chavetas, como vão poder ver no exemplo seguinte. With this feature can boot the properties of an object once in the same statement, using curly braces, and will be able to see the following example.
Neste exemplo, criámos uma classe Citizen com algumas propriedades. In this example, we created a class Citizen with some properties. Na função main, temos primeiro a declaração do objecto bill da maneira tradicional, e depois a declaração do objecto steve , através dos object initializers: In the main function, we have the first statement of the purpose of the bill the traditional way, and after the declaration of the object steve, through the object initializers:
using System; namespace ConsoleApplication { class Program { static void Main(string[] args) { Citizen bill = new Citizen(); bill.Age = 40; bill.FirstName = "Bill"; bill.LastName = "Gates"; bill.Gender = Genders.Male; bill.PrintInfo(); Citizen steve = new Citizen() {FirstName = "Steve", LastName = "Jobs", Age = 43, Gender = Genders.Male}; steve.PrintInfo(); Console.ReadKey(); } } public enum Genders { Male = 0, Female = 1 } public class Citizen { private string firstName; private int age; private string lastName; private Genders gender; public string FirstName { get { return firstName; } set { firstName = value; } } public int Age { get { return age; } set { age = value; } } public string LastName { get { return lastName; } set { lastName = value; } } public Genders Gender { get { return gender; } set { gender = value; } } public void PrintInfo() { Console.WriteLine("Name: {0} \nLastName: {1} \nAge: {2} \nGender: {3}", firstName, lastName, age, gender); } } } using System; namespace ConsoleApplication class Program ((static void Main (string [] args) (Citizen bill = new Citizen (); bill.Age = 40; bill.FirstName = "Bill"; bill.LastName = "Gates"; bill . Gender = Genders.Male; bill.PrintInfo (); Citizen steve = new Citizen () = (FirstName "Steve", LastName = "Jobs", = 43 Age, Gender = Genders.Male); steve.PrintInfo (); Console.ReadKey ();)) public enum Genders (= 0 Male, Female = 1) public class Citizen (private string firstName; private int age; private string lastName; private Genders gender; public string FirstName (get (return firstName;) (September firstName = value;)) public int Age (get (return age;) (September age = value;)) public string LastName (get (return lastName;) (September lastName = value;)) public Genders Gender (get ( return gender;) (September gender = value;)) public void PrintInfo () (Console.WriteLine ( "Name: (0) \ nLastName: (1) \ nAge: (2) \ nGender: (3)", firstName, lastName, age, gender);))) Os Object Initializers tornam-se especialmente úteis quando os utilizamos em conjunto com o LINQ, nas query expressions . The Object Initializers become especially useful when used in conjunction with the LINQ in query expressions. Numa cláusula select, a query expression pode transformar, na própria query, os objectos que queremos seleccionar. In a select clause, the query expression can change in the query, the objects that we want to select. Desta forma podemos obter apenas os dados que desejamos, por exemplo, imagem que só queriamos saber o primeiro e último nome dos objectos do tipo Citizen . Thus we can only obtain the data they want, for example, image queriamos know that only the first and last names of objects of type Citizen. Nesse caso teriamos um select deste género: In this case would have such a select:
var citizenNames = from c in citizens select new {c.FirstName, c.LastName}; foreach (var cit in citizenNames) { Console.WriteLine("{0} {1}",cit.FirstName, cit.LastName); } var citizenNames = c from citizens in select new (c.FirstName, c.LastName); foreach (var in citizenNames cit) (Console.WriteLine ( "(0) (1)", cit.FirstName, cit.LastName);) O objecto citizenNames, contem novos objectos com apenas as propriedades FirstName e LastName. The object citizenNames, contains new objects with only the properties FirstName and LastName. Com os Object Initializers poderíamos até alterar o nome da propriedade, utilizando a sintaxe seguinte: With the Object Initializers could even change the name of the property, using the syntax:
var citizenNames = from c in citizens select new {c.FirstName, Name = c.LastName}; foreach (var cit in citizenNames) { Console.WriteLine("{0} {1}",cit.FirstName, cit.Name); } var citizenNames = c from citizens in select new (c.FirstName, c.LastName Name =); foreach (var in citizenNames cit) (Console.WriteLine ( "(0) (1)", cit.FirstName, cit.Name) ;) Mais uma vez, podemos ver que com a utilização das novas funcionalidade do C# 3.0 encurtamos o número de linhas de código produzidas. Again, we can see that with the use of new functionality of C # 3.0 encurtamos the number of lines of code produced.
Se gostaram deste artigo subscrevam a feed RSS do istomesmo, para ficarem actualizados sobre os últimos artigos. If you liked this article subscribe to the RSS feed istomesmo, to be updated on the latest articles.
» Subscrevam aqui a fedd RSS « "Subscribe here fedd RSS '
Obtenha mais informações sobre a fedd RSS aqui Learn more about the RSS fedd here


Últimos Comentários Last comments