c# - 动态检索 NativeActivity 的变量和参数值
问题描述
当我将以下代码(C#)作为自定义活动运行时(已编译的 .dll 被添加到 nuget 包并在 UiPath 序列中使用一些用户定义的变量/参数触发。我能够检索变量的名称及其类型,但我找不到正确的语法来检索该值(我只想将其转换为字符串,不需要做任何花哨的事情)。我可以访问一些属性,所以我知道我很接近。我已经完成了我的最好阅读文档,但在这种情况下,对我来说可能有点抽象。我已经经历了许多互动并尽可能多地搜索了互联网,但我似乎无法弄清楚。
using Newtonsoft.Json.Linq;
using System;
using System.Activities;
using System.Activities.Hosting;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
namespace AutoLog
{
public sealed class GetRootActivity : NativeActivity
{
public OutArgument<string> variables { get; set; }
protected override void Execute(NativeActivityContext context)
{
this.variables.Set((ActivityContext)context, Library.getLocalVariables(context));
}
protected override void CacheMetadata(NativeActivityMetadata metadata)
{
base.CacheMetadata(metadata);
metadata.AddDefaultExtensionProvider<GetRootActivity.WorkflowInstanceInfo>((Func<GetRootActivity.WorkflowInstanceInfo>)(() => new GetRootActivity.WorkflowInstanceInfo()));
}
public class Library
{
public static string getLocalVariables(NativeActivityContext context)
{
var properties = context.DataContext.GetProperties();
JArray variables = new JArray();
foreach(PropertyDescriptor p in properties)
{
JObject variable = new JObject();
variable["name"] = p.Name;
variable["type"] = p.PropertyType.ToString();
string string_value = "";
try
{
var myValue = context.DataContext.GetType().GetProperty(p.Name).GetValue(context.DataContext, null);
string_value = myValue.ToString();
}
catch(Exception e)
{
}
variable["value"] = string_value;
variables.Add(variable);
}
return variables.ToString();
}
}
}
}
下面是它生成的 JSON 示例,如您所见,“value”字段为空
[
{
"name": "a",
"type": "System.String",
"value": ""
},
{
"name": "b",
"type": "System.Boolean",
"value": ""
},
{
"name": "c",
"type": "System.Int32",
"value": ""
},
{
"name": "test",
"type": "System.String",
"value": ""
},
{
"name": "f",
"type": "System.String",
"value": ""
}
]
解决方案
var myValue = context.DataContext.GetType().GetProperty(p.Name).GetValue(context.DataContext, null);
string_value = myValue.ToString();
可以改为
string_value = p.GetValue(context.DataContext) as String;
我之前曾尝试过这种方法,但试图让演员阵容动态化,显然我从未尝试过更简单的解决方案。
推荐阅读
- go - 如何让 main() 等待直到 init() 在 golang 中完成?
- json - 如何给一些时间(60 秒)快速重新发送 OTP 按钮
- excel - 在不同列中具有多个条件的 VLOOKUP
- django - Django与另一个python应用程序通信?
- python - keras “你必须在使用它之前编译你的模型。” 即使在编译之后
- javascript - 使用 React-hook 的函数组件是否可以从类组件内部渲染
- c++ - 如何以最优雅的 c++ 方式设计一个已经预定义标准颜色的颜色类?
- css - PHP选择下拉菜单多列,多种颜色
- python - 如何将 python 操作的结果发布为 SNS 消息
- migration - 通过导入 zip 文件恢复代理会给出“平台不支持的语言”错误 Dialogflow