我有以下WF活動,我已創建這些活動來測試執行(vb)表達式的一組「變量」表達。Windows Workflow自定義活動:評估引用變量的表達式時出錯
public class ExpressionEncapsulationActivity : NativeActivity<bool>
{
private readonly Collection<Variable> _variables = new Collection<Variable>();
private readonly Collection<Activity> _activities = new BindingList<Activity>();
private Assign _expressionEvaluationChild { get; set; }
private Variable<bool> _expressionResultVariable;
public Collection<Variable> Variables { get { return _variables; } }
public InArgument<bool> Expression { get; set; }
protected override void CacheMetadata(NativeActivityMetadata metadata)
{
base.CacheMetadata(metadata);
DisplayName = "Expression Encapsulation";
metadata.SetVariablesCollection(Variables);
metadata.SetChildrenCollection(_activities);
_expressionResultVariable = new Variable<bool>("evalResult");
_expressionEvaluationChild = new Assign()
{
DisplayName = "Expression Encapsulation Assign",
To = new OutArgument<bool>(_expressionResultVariable),
Value = new InArgument<bool>((ctx) => Expression.Get(ctx))
};
metadata.AddImplementationVariable(_expressionResultVariable);
metadata.AddImplementationChild(_expressionEvaluationChild);
}
protected override void Execute(NativeActivityContext context)
{
context.ScheduleActivity(_expressionEvaluationChild, OnExpressionEvaluationComplete);
}
protected void OnExpressionEvaluationComplete(NativeActivityContext context, ActivityInstance completedActivity)
{
Result.Set(context, _expressionResultVariable.Get(context));
}
}
而且我想測試活動如下: (類ForEachActivityItem簡單,上有一個id屬性)
var testVarItem = new ForEachActivityItem()
{
Id = 2
};
var workflow = new ExpressionEncapsulationActivity()
{
Variables =
{
new Variable<ForEachActivityItem>("var", (ctx) => testVarItem)
},
Expression = new InArgument<bool>(new VisualBasicValue<bool>("var.Id = 1"))
};
var result = WorkflowInvoker.Invoke(workflow);
Assert.IsFalse(result, "Test #1");
但這種測試引發錯誤:
System.Activities.InvalidWorkflowException: The following errors were encountered while processing the workflow tree: 'VisualBasicValue': Compiler error(s) encountered processing expression "var.Id = 2". 'var' is not declared. It may be inaccessible due to its protection level.
我不明白爲什麼變量(var)不可用於表達式,因爲它在表達式的執行上下文的「父」活動中聲明(即Assign ch在ExpressionEncapsulationActivity活動內創建的活動活動)。
可能值得注意的是,如果傳入的表達式不引用變量(例如「1 = 1」),則測試可以工作。同樣有趣的是,如果我使用Sequence
活動,設置其變量並向其添加一個Assign
子活動來評估表達式,則我可以使用獲得此類表達式。