从一个完全限定的方法名中拆分参数

本文关键字:方法 参数 拆分 一个 | 更新日期: 2023-09-27 18:06:56

我正在解析编译后的XML文档,这些文档是在我们编译应用程序时生成的。我有一个成员,看起来像这样:

<member name="M:Core.CachedType.GetAttributes(System.Reflection.PropertyInfo,System.Func{System.Attribute,System.Boolean})">
    <summary>
    <para>
    Gets all of the attributes for the Type that is associated with an optional property and optionally filtered.
    </para>
    </summary>
    <param name="property">The property.</param>
    <param name="predicate">The predicate.</param>
    <returns>Returns a collection of Attributes</returns>
</member>

为了通过反射获得MethodInfo,我必须将Type参数传递给Type. getmethodinfo()方法。这需要我拆分参数并获取它们的类型。最初这很简单,我做了以下操作(使用示例成员字符串):

string elementName = "M:Core.CachedType.GetAttributes(System.Reflection.PropertyInfo,System.Func{System.Attribute,System.Boolean})";
string[] methodSignature = elementName.Substring(2, elementName.Length - 3).Split('(');
string methodName = methodSignature[0].Split('.').LastOrDefault();
string[] methodParameters = methodSignature[1].Split(',');

在本例中,methodSignature包含两个值

  • Core.CachedType.GetAttributes
  • System.Reflection.PropertyInfo System.Func {System.Attribute, System.Boolean}

这给了我方法本身的名称,然后是它可以接受的参数列表。methodParameters数组以逗号分隔的方法参数包含每个参数。这在一开始工作得很好,直到我遇到有超过1个泛型参数的类型。通用参数也用逗号分隔,这显然会导致意想不到的副作用。在上面的例子中,methodParameters包含

  • System.Reflection.PropertyInfo
  • System.Func {System.Attribute
  • 系统。布尔}

可以看到,它将Func<Attribute, bool>类型拆分为数组中的两个不同元素。我要避免这种情况。我认为这意味着不使用string.Split,这很好。是否有一种现有的方法来处理这个问题,我没有想到在。net中,或者我需要写一个小解析器来处理这个问题?

从一个完全限定的方法名中拆分参数

您只需要编写一个可以处理嵌套大括号的自定义解析器。下面这行:

IEnumerable<string> GetParameterNames(string signature)
{
    var openBraces = 0;
    var buffer = new StringBuilder();
    foreach (var c in signature)
    {
        if (c == '{')
        {
            openBraces++;
        }
        else if (c == '}')
        {
            openBraces--;
        }
        else if (c == ',' && openBraces == 0)
        {
            if (buffer.Length == 0)
                throw new FormatException(); //syntax is not right.
            yield return buffer.ToString();
            buffer.Clear();
            continue;
        }
        buffer.Append(c);
    }
    if (buffer.Length == 0 || openBraces != 0)
        throw new FormatException(); //syntax is not right.
    yield return buffer.ToString();
}

这是写在我的手机上的,所以肯定会有错误,但你应该明白。您可以递归地调用它来解析嵌套的类型列表。