sabato 7 gennaio 2012

NETMF Extension Methods

Una delle caratteristiche più accattivanti di C# sono gli extension methods, peccato che per il .NET MicroFW non siano disponibili. Infatti tentando di utilizzarli si ottiene il seguente errore:

Cannot define a new extension method because the compiler required type 'System.Runtime.CompilerServices.ExtensionAttribute' cannot be found. Are you missing a reference to System.Core.dll?

Cercando una possibile soluzione ho trovato questo post che riporta la soluzione al problema:

using System;
using System;
using System.Threading;
 
using Microsoft.SPOT;
using Microsoft.SPOT.Hardware;
 
// Required for NETMF to recognized extension methods
namespace System.Runtime.CompilerServices
{
    [AttributeUsage(AttributeTargets.Assembly | AttributeTargets.Class | AttributeTargets.Method)]
    public sealed class ExtensionAttribute : Attribute { }
}
 
// Extension methods for byte[] - typically would be put in a separate file
public static class ByteArrayExtensions
{
    // Method to create a string from UTF8-encoded bytes - be careful about null "this" being passed in
    public static string ToStringFromUTF8(this byte[] bytes)
    {
        return null == bytes ? String.Empty : new String(System.Text.Encoding.UTF8.GetChars(bytes));
    }
}


Come si vede dal codice riportato il trucco è definire l’attributo ExtensionAttribute.

Nessun commento:

Posta un commento