開發環境準備:
- Microsoft Visual Studio with the .NET C# desktop development workload installed.
- NuGet Package Explorer.
自定義Activity分兩種,CodeActivity和NativeActivity。簡單的區分就是CodeActivity只是執行一段代碼,NativeActivity的效果就像內置Activities一樣,它們實際上就是不同Activity的父類,實現的時候選擇繼承哪個類,你的Activity就是屬於哪個分類。
我們這裏是實現CodeActivity,NativeActivity請看開源代碼的實現。
功能是把特定分隔符連接的字符串分割開,然後隨機返回其中的某一個。應用在給選擇框一個隨機的值。因爲主要是學習的目的,所以實際上並沒有跟選擇框有太大的關聯,只是對字符做了處理而已。
自定義Activity分兩步,首先通過C#語言來編寫你的Activity邏輯,編譯生成.dll文件,然後通過NuGet Package Explorer打包。
下面跟着提示一步一步創建C#項目:
- Launch Microsoft Visual Studio.
- Click 文件 > 創建 > 項目 (shortcut: Ctrl + Shift + N). The New Project window is displayed.
- Click Visual C#. The list of all dependencies using C# is displayed.
- 給你的Activity取個名字, 這裏是 “SelectRandomItem”。
- 選擇類庫(.NET Framework) and click OK. 這樣才能把項目導出爲 .dll文件。
- Click 項目 > 添加引用….
- 分別搜索
System.Activities
和System.ComponentModel.Composition
引用,並勾選。 - Click the OK button.這樣就可以在代碼中使用
System.Activities
和System.ComponentModel.Composition
這兩個基礎組件了。
下面是已添加註釋的實現代碼:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Text.RegularExpressions;
using System.Activities;
using System.ComponentModel;
namespace RandomChoiceText
{
public class SelectRandomItem : CodeActivity
{
//參數類型,輸入或者輸出,或者兩者都是
[Category("Input")]
//必須參數
[RequiredArgument]
public InArgument<String> FullText { get; set; }
[Category("Input")]
//參數默認值
[DefaultValue("\r\n")]
public InArgument<String> Separator { get; set; }
[Category("Output")]
public OutArgument<String> ChoiceResult { get; set; }
/**
* Execute是CodeActivity必須重載的方法
* 處理邏輯根據Separator指定的分割符分割FullText
* 然後隨機返回其中一個
*
**/
protected override void Execute(CodeActivityContext context)
{
//所有的參數取值、賦值都是通過context
var fullText = FullText.Get(context);
var separator = Separator.Get(context);
string[] items = Regex.Split(fullText, separator, RegexOptions.IgnoreCase);
Random ran = new Random();
var result = items[ran.Next(items.Length)];
ChoiceResult.Set(context, result);
}
}
}
然後點擊 生成 > 生成 SelectRandomItem。在輸出欄找到SelectRandomItem.dll文件所在位置,準備下一步打包使用。