首页 > 解决方案 > 动态检索 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": ""
  }
]

标签: c#.netwpf

解决方案


var myValue = context.DataContext.GetType().GetProperty(p.Name).GetValue(context.DataContext, null);
string_value = myValue.ToString();

可以改为

string_value = p.GetValue(context.DataContext) as String;

我之前曾尝试过这种方法,但试图让演员阵容动态化,显然我从未尝试过更简单的解决方案。


推荐阅读