As you may know, Microsoft is getting into the open source community with the ASP.NET and DNX with the mono project.
The .NET Execution Environment (DNX) is a software development kit which allows you to run .NET applications on Windows, Mac, and Linux using different frameworks such as .NET framework, .NET Core, and Mono. However, everything are not roses. There are many incomplete libraries, incompatibilities, lack of documentation, and most of the examples such as doing SQL or SOAP do not work depending on which the library targets you are planning to code for. Therefore, I decided to test the basics on all the library targets. I am starting with DNX451.
Attributes seems to be working fine in DNX451 with C#. Below is a code example for those who wish to play with it.
Program.csusing System; namespace ConsoleApp1 { public class Program { public void Main(string[] args){ Console.WriteLine("Main()"); displayWhichDnxIsCompilingOn(); attributeExample() } private void displayWhichDnxIsCompilingOn(){ #if DNX451 Console.WriteLine("Compiled on DNX451: .NET Framework"); #endif #if DNXCORE50 Console.WriteLine("Compiled on DNXCORE50: .NET Core 5"); #endif } private void attributeExample(){ AttributeExample ae = new AttributeExample(); ae.printAuthorsUsingAttribute(typeof(ExampleA.ExampleA)); } } } |
AttributeExample.cs
using System; namespace ConsoleApp1 { public class AttributeExample { public AttributeExample(){ Console.WriteLine("AttiruteExample"); } public void printAuthorsUsingAttribute(Type t){ Console.WriteLine("PrintAuthorsUsingAttribute()"); Console.WriteLine("Authors for {0}", t); Attribute[] attributes = Attribute.GetCustomAttributes(t); foreach(Attribute attribute in attributes){ if (attribute is DocAttribute){ DocAttribute doc = (DocAttribute) attribute; Console.WriteLine("-> Author: {0}", doc.author); } } } } } |
DocAttribute.cs
using System; [AttributeUsage(AttributeTargets.All, AllowMultiple = true)] public class DocAttribute : Attribute { public DocAttribute(string author){ this.author = author; } public readonly string author; } |
ExampleA.cs
using System; namespace ExampleA { [Doc("Alejandro")] [Doc("Diego")] public class ExampleA{ [Doc("Mengano")] public ExampleA(){ Console.WriteLine("ExampleA()"); } [Doc("Matias")] public void sayHello(){ Console.WriteLine("Hello from ExampleA!"); } } } |
Output:AGCRM-MacBook-Pro:Examples user$ dnx . me Main() Compiled on DNX451: .NET Framework AttiruteExample PrintAuthorsUsingAttribute() Authors for ExampleA.ExampleA -> Author: Diego -> Author: Alejandro |
© 2015, Alejandro G. Carlstein Ramos Mejia. All rights reserved.