Created
March 26, 2017 03:15
-
-
Save vitormeriat/eb68005cc53f307068b3bf5b53b06cbd to your computer and use it in GitHub Desktop.
POST: Como retornar um tipo anônimo por método
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
using System; | |
using System.Collections.Generic; | |
using System.Linq; | |
using System.Text; | |
namespace TiposAnonimos | |
{ | |
class Program | |
{ | |
static void Main(string[] args) | |
{ | |
#region ====== Exemplo 1 ====== | |
// Declaração padrão de um Tipo Anônimo.. | |
var cliente = new | |
{ | |
Empresa = "Sr.Nimbus", | |
Name = "Vitor Merat", | |
Admissao = new DateTime(2011, 01, 01), | |
Idade = 26 | |
}; | |
#endregion | |
#region ====== Exemplo 2 ====== | |
// *** Criar tipos Complexos 'na mosca' | |
// Observe o membro Contatos que é um outro tipo anônimo aninhado no primeiro tipo. | |
var clienteContato = new | |
{ | |
Empresa = "Sr.Nimbus", | |
Name = "Vitor Merat", | |
Admissao = new DateTime(2011, 01, 01), | |
Idade = 26, | |
Contatos = new | |
{ | |
Telefone = "61 3121-1211", | |
Fax = "61 3231-1211", | |
Email = "[email protected]" | |
} | |
}; | |
#endregion | |
#region ====== Exemplo 3 ====== | |
// Não é possível ter acesso as propriedades. | |
object objeto = RetornoAnonimoPorObject(); | |
//o. ??? | |
var tipado = ConverteTiposPara(objeto, new { Nome = "", Cidade = "" }); | |
// Agora podemos utilizar as propriedades | |
Console.WriteLine("Nome={0}, Cidade={1}", tipado.Nome, tipado.Cidade); | |
#endregion | |
} | |
/// <summary> | |
/// Método que retorna um objeto do tipo anônimo | |
/// </summary> | |
/// <returns></returns> | |
static object RetornoAnonimoPorObject() | |
{ | |
return new { Nome = "Vitor Meriat", Cidade = "Brasília" }; | |
} | |
/// <summary> | |
/// Graças ao tipo de inferência ao chamar métodos é possível converter o objeto para escrever sem saber o nome do tipo | |
/// </summary> | |
/// <typeparam name="T"></typeparam> | |
/// <param name="objeto"></param> | |
/// <param name="tipo"></param> | |
/// <returns></returns> | |
static T ConverteTiposPara<T>(object objeto, T tipo) | |
{ | |
return (T)objeto; | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment