Xamarin Shared Library and PCL

2019-01-17 07:36发布

问题:

What is the exact difference between xamarin shared project and portable class library?

When to use shared library and when to use portable class library?

Is this possible to write native functionality in shared projects like showing alert,accessing camera and use it for both android and iOS?

Can anyone please explain me.

回答1:

  • In shared projects each code file will be compiled for each destination (Android, iOS, Windows Phone etc). You are able to include platform specific code by using #if compiler directives. When you want to access the camera you need to write the access code inside an #if block for all destinated platforms. This can mess up your code but it can be easier to find the different implementations. Learn more: http://developer.xamarin.com/guides/cross-platform/application_fundamentals/shared_projects/
  • Protable Class Libraries (PCL) are compiled against a general .NET subset which is compatible to all platforms you want. So you can access System.Net.Http but you cannot access any platform specific code. If you want to access the camera inside the PCL code then you need to access it by a generalized interface via dependency injection. There are some pretty good frameworks helping you to archieve this goal. One of the most famous is MVVMCross (https://github.com/MvvmCross/MvvmCross/wiki). Learn more about PCL: http://developer.xamarin.com/guides/cross-platform/application_fundamentals/building_cross_platform_applications/sharing_code_options/#Portable_Class_Libraries

I personally perefer PCLs because the code is much easier to read without any compiler directives. Using MVVMCross you are able to use plenty of plugins via NuGet. So you don't need to write your own classes for camera access, showing alerts etc.