Xamarin Android 和 iOS 中的 Visual BasicVisual Basic in Xamarin Android and iOS

下载示例 下载示例Download Sample Download the sample

TaskyVB示例应用程序演示如何 Visual Basic 编译到 .NET Standard 库中的代码如何与 Xamarin 一起使用。The TaskyVB sample application demonstrates how Visual Basic code compiled into a .NET Standard library can be used with Xamarin. 下面是在 Android 和 iOS 上运行的结果应用的一些屏幕截图:Here are some screenshots of the resulting apps running on Android and iOS:

Android 和 iOS 运行使用 Visual Basic 生成的应用Android and iOS running an app built with Visual Basic

示例中的 Android 和 iOS 项目都是用编写的C#。The Android and iOS projects in the example are all written in C#. 每个应用程序的用户界面都是使用本机技术生成的,而 TodoItem 管理由 Visual Basic 使用 XML 文件 .NET Standard 库提供(出于演示目的,而不是完整数据库)。The user interface for each application is built with native technologies, while the TodoItem management is provided by the Visual Basic .NET Standard library using an XML file (for demonstration purposes, not a full database).

示例演练Sample walkthrough

本指南讨论如何在适用于 iOS 和 Android 的TaskyVB Xamarin 示例中实现 Visual Basic。This guide discusses how Visual Basic has been implemented in the TaskyVB Xamarin sample for iOS and Android.

备注

继续本指南之前,请查看Visual Basic 和 .NET Standard上的说明。Review the instructions on Visual Basic and .NET Standard before continuing with this guide.

有关如何使用共享用户界面 Visual Basic 代码构建应用的说明,请参阅使用 Visual Basic 说明的 Xamarin。Refer to the Xamarin.Forms using Visual Basic instructions to see how to build an app with shared user-interface Visual Basic code.

VisualBasicNetStandardVisualBasicNetStandard

Visual Basic .NET Standard 库只能在 Windows 上的 Visual Studio 中创建。Visual Basic .NET Standard libraries can only be created in Visual Studio on Windows. 示例库包含应用程序在以下 Visual Basic 文件中的基础知识:The example library contains the basics of our application in these Visual Basic files:

  • TodoItemTodoItem.vb
  • TodoItemManagerTodoItemManager.vb
  • TodoItemRepositoryXMLTodoItemRepositoryXML.vb
  • XmlStorageXmlStorage.vb

TodoItemTodoItem.vb

此类包含要在整个应用程序中使用的业务对象。This class contains the business object to be used throughout the application. 它将在 Visual Basic 中定义,并与编写的 Android 和 iOS 项目共享C#。It will be defined in Visual Basic and shared with the Android and iOS projects that are written in C#.

类定义如下所示:The class definition is shown here:

Public Class TodoItem
    Property ID() As Integer
    Property Name() As String
    Property Notes() As String
    Property Done() As Boolean
End Class

该示例使用 XML 序列化和反序列化来加载并保存 TodoItem 对象。The sample uses XML serialization and de-serialization to load and save the TodoItem objects.

TodoItemManagerTodoItemManager.vb

管理器类提供可移植代码的 "API"。The Manager class presents the ‘API’ for the portable code. 它为 TodoItem 类提供基本的 CRUD 操作,但不实现这些操作。It provides basic CRUD operations for the TodoItem class, but no implementation of those operations.

Public Class TodoItemManager
    Private _repository As TodoItemRepositoryXML
    Public Sub New(filename As String)
        _repository = New TodoItemRepositoryXML(filename, storage)
    End Sub
    Public Function GetTask(id As Integer) As TodoItem
        Return _repository.GetTask(id)
    End Function
    Public Function GetTasks() As List(Of TodoItem)
        Return New List(Of TodoItem)(_repository.GetTasks())
    End Function
    Public Function SaveTask(item As TodoItem) As Integer
        Return _repository.SaveTask(item)
    End Function
    Public Function DeleteTask(item As TodoItem) As Integer
        Return _repository.DeleteTask(item.ID)
    End Function
End Class

构造函数使用 IXmlStorage 的实例作为参数。The constructor takes an instance of IXmlStorage as a parameter. 这样,每个平台都可以提供自己的工作实现,同时仍允许可移植代码描述可共享的其他功能。This allows each platform to provide its own working implementation while still letting the portable code describe other functionality that can be shared.

TodoItemRepositoryTodoItemRepository.vb

存储库类包含用于管理 TodoItem 对象列表的逻辑。The repository class contains the logic for managing the list of TodoItem objects. 下面显示了完整的代码-逻辑存在,目的是为了在 TodoItems 中对其进行管理,并从集合中删除一个唯一的 ID 值。The complete code is shown below – the logic exists mainly to manage a unique ID value across the TodoItems as they are added and removed from the collection.

Public Class TodoItemRepositoryXML
    Private _filename As String
    Private _storage As IXmlStorage
    Private _tasks As List(Of TodoItem)

    ''' <summary>Constructor</summary>
    Public Sub New(filename As String)
        _filename = filename
        _storage = New XmlStorage
        _tasks = _storage.ReadXml(filename)
    End Sub
    ''' <summary>Inefficient search for a Task by ID</summary>
    Public Function GetTask(id As Integer) As TodoItem
        For t As Integer = 0 To _tasks.Count - 1
            If _tasks(t).ID = id Then
                Return _tasks(t)
            End If
        Next
        Return New TodoItem() With {.ID = id}
    End Function
    ''' <summary>List all the Tasks</summary>
    Public Function GetTasks() As IEnumerable(Of TodoItem)
        Return _tasks
    End Function
    ''' <summary>Save a Task to the Xml file
    ''' Calculates the ID as the max of existing IDs</summary>
    Public Function SaveTask(item As TodoItem) As Integer
        Dim max As Integer = 0
        If _tasks.Count > 0 Then
            max = _tasks.Max(Function(t As TodoItem) t.ID)
        End If
        If item.ID = 0 Then
            item.ID = ++max
            _tasks.Add(item)
        Else
            Dim j = _tasks.Where(Function(t) t.ID = item.ID).First()
            j = item
        End If
        _storage.WriteXml(_tasks, _filename)
        Return max
    End Function
    ''' <summary>Removes the task from the XMl file</summary>
    Public Function DeleteTask(id As Integer) As Integer
        For t As Integer = 0 To _tasks.Count - 1
            If _tasks(t).ID = id Then
                _tasks.RemoveAt(t)
                _storage.WriteXml(_tasks, _filename)
                Return 1
            End If
        Next
        Return -1
    End Function
End Class

备注

此代码是一个非常基本的数据存储机制的示例。This code is an example of a very basic data-storage mechanism. 提供它是为了演示 .NET Standard 库如何针对接口编写代码,以访问特定于平台的功能(在此情况下,加载和保存 XML 文件)。It is provided to demonstrate how a .NET Standard library can code against an interface to access platform-specific functionality (in this case, loading and saving an XML file). 它不是一种生产质量的数据库备选方案。It it not intended to be a production-quality database alternative.

Android 和 iOS 应用程序项目Android and iOS application projects

iOSiOS

在 iOS 应用程序中,将在AppDelegate.cs文件中创建 TodoItemManagerXmlStorageImplementation,如下面的代码段所示。In the iOS application the TodoItemManager and the XmlStorageImplementation are created in the AppDelegate.cs file as shown in this code snippet. 前四行只是生成数据将存储到的文件的路径;最后两行显示两个实例化的类。The first four lines are just building the path to the file where data will be stored; the final two lines show the two classes being instantiated.

var xmlFilename = "TodoList.xml";
string documentsPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal); // Documents folder
string libraryPath = Path.Combine(documentsPath, "..", "Library"); // Library folder
var path = Path.Combine(libraryPath, xmlFilename);

TaskMgr = new TodoItemManager(path);

AndroidAndroid

在 Android 应用程序中,将在Application.cs文件中创建 TodoItemManagerXmlStorageImplementation,如下面的代码段所示。In the Android application the TodoItemManager and the XmlStorageImplementation are created in the Application.cs file as shown in this code snippet. 前三行只是生成存储数据的文件的路径;最后两行显示两个实例化的类。The first three lines are just building the path to the file where data will be stored; the final two lines show the two classes being instantiated.

var xmlFilename = "TodoList.xml";
string libraryPath = Environment.GetFolderPath(Environment.SpecialFolder.Personal);
var path = Path.Combine(libraryPath, xmlFilename);

TaskMgr = new TodoItemManager(path);

应用程序代码的其余部分主要涉及用户界面,并使用 TaskMgr 类加载并保存 TodoItem 类。The rest of the application code is primarily concerned with the user interface and using the TaskMgr class to load and save TodoItem classes.

Visual Studio 2019 for MacVisual Studio 2019 for Mac

警告

Visual Studio for Mac 不支持编辑 Visual Basic 语言–没有用于创建 Visual Basic 项目或文件的菜单项。Visual Studio for Mac does NOT support editing the Visual Basic language – there are no menu items for creating Visual Basic projects or files. 如果打开 .vb ,则没有语言语法突出显示、自动完成或 IntelliSense。If you open a .vb there is no language syntax highlighting, autocomplete, or IntelliSense.

Visual Studio 2019 for Mac_可以_编译在 Windows 上创建的 visual studio .NET Standard 项目,因此 iOS 应用可以引用这些项目。Visual Studio 2019 for Mac can compile Visual Studio .NET Standard projects created on Windows, so iOS apps can reference those projects.

Visual Studio 2017 根本_无法_生成 Visual Basic 项目。Visual Studio 2017 cannot build Visual Basic projects at all.

总结Summary

本文演示了如何使用 Visual Studio 和 .NET Standard 库在 Xamarin 应用程序中使用 Visual Basic 代码。This article has demonstrated how to consume Visual Basic code in Xamarin applications using Visual Studio and .NET Standard libraries. 尽管 Xamarin 不支持直接 Visual Basic,但将 Visual Basic 编译到 .NET Standard 库允许将使用 Visual Basic 编写的代码包含在 iOS 和 Android 应用中。Even though Xamarin does not support Visual Basic directly, compiling Visual Basic into a .NET Standard library allows code written with Visual Basic to be included in iOS and Android apps.