gpt4 book ai didi

workflow-foundation - 从 WF 4 事件动态设置外部范围中的变量

转载 作者:行者123 更新时间:2023-12-01 14:21:15 26 4
gpt4 key购买 nike

如何在 .NET 4 下的 Windows Workflow Foundation 事件中动态设置父作用域中的变量值?

失败的尝试(放置在工作流上的序列事件,其中序列具有名为 Test 的 int 变量):

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;
}

这会导致:

System.InvalidOperationException was unhandled by user code
Message=Activity '1.2: CodeActivity1' cannot access this variable because it is declared at the scope of activity '1.1: Sequence'. An activity can only access its own implementation variables.

它确实找到了变量;它只是无法获取或设置其值。

变量名称(上例中的“Test”)直到运行时才知道。

最佳答案

处理此问题的正常方法是定义 OutArgument 并在工作流设计器中将 OutArgument 绑定(bind)到您的变量。在事件中,您只处理论证。使用 NativeActivity 会为您提供一个名为 Result 的 OutArgument,但只需添加 OUTArgument 的属性就可以了。

另一个好处是您不需要知道用于存储结果的“神奇”变量名称。

更新,因为下面评论中的代码不可读。

尝试在它爆炸的行之前添加以下内容:

var pi = context.GetType().GetProperty("AllowChainedEnvironmentAccess", BindingFlags.NonPublic | BindingFlags.Instance); 
pi.SetValue(context, true, null);

完全不支持,所以请小心使用:-)

关于workflow-foundation - 从 WF 4 事件动态设置外部范围中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4340561/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com