首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> .NET 網頁程式設計 >> 關於.NET

Visual Studio DSL 入門:為狀態機設計器添加驗證規則

     編輯:關於.NET

承接上一節對設計器顯示層面的完善,本節將深入狀態機設計器的邏輯細節,為設計器添加邏輯規則,為後續代碼生成奠定基礎。我們將使用 VS.NET DSL 的規則機制來實現 Transition 標籤屬性與 Event、Condition、Action 三屬性的雙向自動同步更新。

屬性關係分析

Transition 類別中幾個關鍵屬性間的互動關係如下:

  1. 編輯 Event、Condition、Action 屬性時,Label 屬性能自動計算顯示,計算邏輯為:Event [Condition] / Action
  2. 修改 Label 屬性時,Event、Condition、Action 的值也能對應自動更新

實作步驟

1. 建立自定義代碼結構

在 DSL 專案下新增 CustomCode 資料夾存放自定義代碼(這是 DSL 開發通用做法),並在其下建立 Validation 資料夾存放手寫的自定義驗證類。

2. 建立規則類別

在 Validation 資料夾下添加 TransitionLabelRule 類別,繼承 ChangeRule,並使用 RuleOn 屬性標記此規則應用到域關係 Transition 上:

using Microsoft.VisualStudio.Modeling;

namespace Company.LanguageSm
{
    [RuleOn(typeof(Transition))]
    public sealed class TransitionLabelRule : ChangeRule
    {
    }
}

3. 實作屬性變更邏輯

覆寫 ElementPropertyChanged 方法,當 Transition 的屬性發生變化時觸發規則。參數 ElementPropertyChangedEventArgs 包含模型元素、編輯的屬性、舊值與新值:

public override void ElementPropertyChanged(ElementPropertyChangedEventArgs e)
{
    Transition t = e.ModelElement as Transition;

    // Event 變更時計算 Label
    if (e.DomainProperty.Id == Transition.EventDomainPropertyId)
        t.Label = ComputeSummary(e.NewValue as string, t.Condition, t.Action);

    // Condition 變更時計算 Label
    else if (e.DomainProperty.Id == Transition.ConditionDomainPropertyId)
        t.Label = ComputeSummary(t.Event, e.NewValue as string, t.Action);

    // Action 變更時計算 Label
    else if (e.DomainProperty.Id == Transition.ActionDomainPropertyId)
        t.Label = ComputeSummary(t.Event, t.Condition, e.NewValue as string);

    // Label 變更時反解 Event、Condition、Action
    else if (e.DomainProperty.Id == Transition.LabelDomainPropertyId)
        ComputeProperties(e.NewValue as string, t);
}

其中 ComputeSummary 由 Event、Condition、Action 計算 Label,ComputeProperties 由 Label 反解三個屬性值。這兩個輔助方法可在下載代碼中查看。

4. 註冊規則使其生效

重新運行專案會發現規則未生效,這是因為還需對 Rule 進行註冊。在 CustomCode 下添加 LanguageSmDomainModel 的 partial 類別,在 GetCustomDomainModelTypes 方法中添加自定義 Rule 集合:

namespace Company.LanguageSm
{
    public partial class LanguageSmDomainModel
    {
        protected override Type[] GetCustomDomainModelTypes()
        {
            return new Type[] { typeof(TransitionLabelRule), };
        }
    }
}

5. 測試驗證

生成並轉換所有範本後測試,修改 Transition 屬性時即可看到規則生效,斷點正常命中,實現了屬性間的雙向自動同步。

本文配套完整原始碼可供下載參考,出處:https://lonely7345.cnblogs.com/

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved