2017年9月9日 星期六

[.NET Standard] Quick start

 .NET Standard

Introduction



The .NET Standard is a formal specification of .NET APIs that are intended to be available on all .NET implementations.  (From .NET Guide)



1.  With .NET Standard, we don't care about platforms, just the Standard’s version and its supported platforms. The Standard library will work on all platforms that support it.
2.  .NET Standard is the replacement for Portable Class Libraries (PCL).


Here are the list of the .NET Standard version and its supported platforms so far.




Let’s make a sample on creating a .NET Standard 2.0 class library and use it on both .NET Core 2.0 and .NET Framework 4.6.2


Environment


Visual Studio 2017 community 15.3.3
.net core 2.0.0-preview1-005977



Implement


Create a .NET Standard class library

First, we will create a .NET Standard class library.



Or use the following command.

$ dotnet new classlib --name MyStandardLib --framework netstandard2.0


Make sure that the class library runs on .NET standard 2.0


<Project Sdk="Microsoft.NET.Sdk">
  <PropertyGroup>
    <TargetFramework>netstandard2.0</TargetFramework>
  </PropertyGroup>
</Project>



Let’s create a Utility class which can sum up the input numbers.

public static class Calculator
{
        public static decimal Sum(decimal[] data)
        {
            decimal sum = 0;
            data.ToList().ForEach(x =>
            {
                sum += x;
            });

            return sum;
        }
}



Reference the .NET Standard class library in .NET Core application


Create an .NET Core console app and reference the .NET Standard class library.

$ dotnet new console --name MyCoreApp  --framework netcoreapp2.0
$ cd MyCoreApp
$ dotnet add MyCoreApp.csproj reference ..\MyStandardLib\MyStandardLib.csproj



Write some sample codes like this…

using MyStandardLib;

class Program
{
        static void Main(string[] args)
        {
            var sum = Calculator.Sum(new decimal[] { 2.5M, 3.5M, 1.1M });

            Console.WriteLine($"Result = {sum}");
            Console.ReadKey();
        }
}


Works like a charm :-)




Reference the .NET Standard class library in .NET frameworks application

Let’s do the same thing on .NET frameworks 4.6.1 application.




The .NET Standard 2.0 class library also works fine on .NET frameworks 4.6.1 or later versions.



But if it’s on an older version of .NET frameworks, we will get this message.






Summary

With .NET Core 2.0 and .NET Standard 2.0 released, I suggest that we should start migrate our projects (and skills) to them.

You can see the latest .NET Core Roadmap here.



                                                





沒有留言:

張貼留言