[英]Split arguments out of a fully qualified method name
我正在解析編譯應用程序時生成的已編譯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
包含兩個值
這給了我方法名稱本身,然后是它可以采用的參數列表。 methodParameters
數組通過分隔逗號的方法參數包含每個參數。 這最初很有用,直到遇到具有多個通用參數的類型。 泛型參數也用逗號分隔,這顯然會導致意外的副作用。 在上面的示例中, methodParameters
包含
如您所見,它將Func<Attribute, bool>
Type拆分為數組中的兩個不同元素。 我需要避免這種情況。 我認為這意味着不使用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();
}
這是寫在我的單元格上,所以它一定有錯誤,但你應該明白這個想法。 您可以遞歸調用此方法來解析嵌套類型列表。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.