BotBuilder CustomRecognizer不起作用

时间:2018-02-24 11:42:35

标签: c# botframework

我正在尝试实现自定义识别器,但无法使其正常工作。 CustomRecognizer.Parse未被调用。

代码示例:

var form = new MyForm();
            var formDialog = new FormDialog<MyForm>(form, MyForm.BuildForm, FormOptions.PromptInStart);
            context.Call(formDialog, OnFormFinished);

    [Serializable]
    public class MyForm
    {
        [Describe("Custom field")]
        [Prompt("Please enter custom field")]
        public string Field { get; set; }

        public static IForm<MyForm> BuildForm()
        {
            return new FormBuilder<MyForm>()
                        .Field(new CustomField<MyForm>(nameof(Field)))
                        .Build();
        }
    }

    public class CustomField<T> : FieldReflector<T> where T : class
    {
        public CustomField(string name, bool ignoreAnnotations = false)
            : base(name, ignoreAnnotations) { }

        public override IForm<T> Form
        {
            set
            {
                base.Form = value;
                SetRecognizer(new CustomRecognizer<T>(this));
            }
        }
    }

    public class CustomRecognizer<T> : RecognizePrimitive<T> where T : class
    {
        public CustomRecognizer(IField<T> field)
            : base(field)
        {
        }

        public override DescribeAttribute ValueDescription(object value)
        {
            return new DescribeAttribute((string)value);
        }

        public override IEnumerable<string> ValidInputs(object value)
        {
            yield return (string)value;
        }

        public override TermMatch Parse(string input)
        {
            TermMatch result = new TermMatch(0, input.Length, 1.0, input);
            return result;
        }

        public override string Help(T state, object defaultValue)
        {
            var prompt = new Prompter<T>(_field.Template(TemplateUsage.StringHelp), _field.Form, null);
            var args = HelpArgs(state, defaultValue);
            return prompt.Prompt(state, _field, args.ToArray()).Prompt;
        }
    }

1 个答案:

答案 0 :(得分:0)

来自SetRecognizer的documentation

  

只有在动态定义字段时才应调用此方法   使用DefineAsyncDelegate,因为识别器通常需要   如果本地化发生变化,通常会发生变化。

因此,如果您将.BuildForm更改为:

public static IForm<MyForm> BuildForm()
{
        return new FormBuilder<MyForm>()

                    .Field(new CustomField<MyForm>(nameof(TestField))
                            .SetDefine(async (state, field) =>
                            {
                                field.SetRecognizer(new CustomRecognizer<MyForm>(field));                                   
                                return true;
                            }))
                    .Build();
}

可在此处找到更多详细信息:https://github.com/Microsoft/BotBuilder/issues/213