Tru*_*ill 2 workflow-foundation workflow-foundation-4
如何在.NET 4下的Windows Workflow Foundation活动中从父作用域动态设置变量值?
失败的尝试(在Sequence具有名为Test的int变量的工作流上删除Sequence活动):
public sealed class CodeActivity1 : NativeActivity
{
protected override void CacheMetadata(NativeActivityMetadata metadata)
{
_locationReferences =
metadata.Environment.GetLocationReferences().ToList();
base.CacheMetadata(metadata);
}
protected override void Execute(NativeActivityContext context)
{
LocationReference locationReference =
_locationReferences.Find(
x => x.Name == "Test" && x.Type == typeof (int));
if (locationReference != null)
{
Console.WriteLine(
locationReference.Name + " " + locationReference.Type);
// Blows up here.
Location location = locationReference.GetLocation(context);
location.Value = 5;
}
}
private List<LocationReference> _locationReferences;
}
Run Code Online (Sandbox Code Playgroud)
这导致:
用户代码未处理System.InvalidOperationException
消息=活动'1.2:CodeActivity1'无法访问此变量,因为它在活动'1.1:Sequence'的范围内声明.活动只能访问自己的实现变量.
它确实找到了变量; 它无法获得或设定其价值.
变量名称(上例中的"Test")直到运行时才会知道.
处理此问题的常规方法是定义OutArgument,并在工作流设计器中将OutArgument绑定到您的变量.在活动中,您只使用参数.使用NativeActivity为您提供名为Result的OutArgument,但只添加OUtArgument属性就可以了.
另一个好处是你不需要知道"魔术"变量名来存储结果.
更新,因为下面评论中的代码是不可读的.
尝试在它爆炸的行之前添加以下内容:
var pi = context.GetType().GetProperty("AllowChainedEnvironmentAccess", BindingFlags.NonPublic | BindingFlags.Instance);
pi.SetValue(context, true, null);
Run Code Online (Sandbox Code Playgroud)
完全不支持所以小心使用:-)
| 归档时间: |
|
| 查看次数: |
4575 次 |
| 最近记录: |