版本:Unity 6 (6000.0)
语言中文
  • C#

QueryEngine<T0>.AddTypeParser

建议更改

成功!

感谢您帮助我们提高 Unity 文档的质量。虽然我们无法接受所有的提交,但我们会阅读来自用户的所有建议的更改,并在适当的时候进行更新。

关闭

提交失败

由于某些原因,无法提交您的建议的更改。请在几分钟后尝试</a>再次提交。感谢您花时间帮助我们提高 Unity 文档的质量。

关闭

取消

声明

public void AddTypeParser(Func<string,ParseResult<TFilterConstant>> parser);

参数

parser 用于确定一个字符串是否可以转换为 TFilterConstant 的回调。获取一个字符串并返回一个 ParseResult 对象。此包含成功标志和成功的转换值(如果成功的话)。

描述

添加类型解析器,解析字符串并返回自定义类型。自定义运算符处理程序使用(参见 AddOperatorHandler)。

<TFilterConstant>: 位于运算符右侧的解析后操作数的类型。

using System.Collections.Generic;
using System.Globalization;
using System.Linq;
using UnityEditor;
using UnityEditor.Search;
using UnityEngine;

static class Example_QueryEngine_AddTypeParser
{
    static List<MyObjectType> s_Data;

    [MenuItem("Examples/QueryEngine/AddTypeParser")]
    public static void RunExample()
    {
        // Set up the query engine
        var queryEngine = new QueryEngine<MyObjectType>();
        queryEngine.AddFilter("id", myObj => myObj.id);
        queryEngine.AddFilter("p", myObj => myObj.position, new[] { "=", "!=" });
        queryEngine.SetSearchDataCallback(myObj => new[] { myObj.id.ToString(), myObj.name });

        // Add a new type parser for Vector2 written as "[x, y]"
        queryEngine.AddTypeParser<Vector2>(s =>
        {
            // If the format requirement is not met, return a failure.
            if (!s.StartsWith("[") || !s.EndsWith("]"))
                return ParseResult<Vector2>.none;

            var trimmed = s.Trim('[', ']');
            var vectorTokens = trimmed.Split(',');
            var vectorValues = vectorTokens.Select(token => float.Parse(token, CultureInfo.InvariantCulture.NumberFormat)).ToList();
            if (vectorValues.Count != 2)
                return ParseResult<Vector2>.none;
            var vector = new Vector2(vectorValues[0], vectorValues[1]);

            // When the conversion succeeds, return a success.
            return new ParseResult<Vector2>(true, vector);
        });
        queryEngine.AddOperatorHandler("=", (Vector2 ev, Vector2 fv) => ev == fv);
        queryEngine.AddOperatorHandler("!=", (Vector2 ev, Vector2 fv) => ev != fv);

        s_Data = new List<MyObjectType>()
        {
            new MyObjectType { id = 0, name = "Test 1", position = new Vector2(0, 0), active = false },
            new MyObjectType { id = 1, name = "Test 2", position = new Vector2(0, 1), active = true },
            new MyObjectType { id = 2, name = "Test 3", position = new Vector2(1, 0), active = false },
            new MyObjectType { id = 3, name = "Test 4", position = new Vector2(1.2f, 0), active = false },
        };

        // Find all items that are located at position [0, 1]
        var query = queryEngine.ParseQuery("p=\"[0, 1]\"");
        var filteredData = query.Apply(s_Data).ToList();
        Debug.Assert(filteredData.Count == 1, $"There should be 1 item in the filtered list but found {filteredData.Count} items.");
        Debug.Assert(filteredData.Contains(s_Data[1]), "Test 2 should be in the list as its position [0, 1].");
    }

    class MyObjectType
    {
        public int id { get; set; }
        public string name { get; set; } = string.Empty;
        public Vector2 position { get; set; } = Vector2.zero;
        public bool active { get; set; }

        public override string ToString()
        {
            return $"({id}, {name}, ({position.x}, {position.y}), {active})";
        }
    }
}