2013-08-27 28 views
-3

函數如何將字符串內容傳遞給下面的「比較器」函數?C#:傳遞字符串以低於

public static void Sort(XmlNodeList nodes, Comparison<XmlElement> comparer) 
{ 
    // The nodes.Count == 0 will break the nodes[0].ParentNode, 
    // the nodes.Count == 1 is pure optimization :-) 
    if (nodes.Count < 2) 
    { 
     return; 
    } 
    var parent = nodes[0].ParentNode; 
    var list = new List<XmlElement>(nodes.Count); 
    foreach (XmlElement element in nodes) 
    { 
     list.Add(element); 
    } 
    list.Sort(Comparer); 
    foreach (XmlElement element in list) 
    { 
     // You can't remove in the other foreach, because it will break 
     // the childNodes collection 
     parent.RemoveChild(element); 
     parent.AppendChild(element); 
    } 
} 

public static int Comparer(XmlElement a, XmlElement b,str strAttributeName) 
{ 
    int aaa = int.Parse(a.Attributes["aa"].Value); 
    int aab = int.Parse(b.Attributes["aa"].Value); 
    int cmp = aaa.CompareTo(aab); 
    if (cmp != 0) 
    { 
     return cmp; 
    } 
    int ba = int.Parse(a.Attributes["b"].Value); 
    int bb = int.Parse(b.Attributes["b"].Value); 
    cmp = ba.CompareTo(bb); 
    return cmp; 
} 

在這裏,我想使a.Attributes["aa"].Valuea.Attributes[strAttributeName].Value在我上面的代碼,使其更通用。我們該怎麼做呢?

請幫忙。

+0

到底是怎麼做到的? 'a.Attributes [strAttributeName] .Value'。課程的類型應該是'string'而不是'str'。 – Rotem

+0

對於初學者來說,你可以將'str strAttributeName'更改爲'string strAttributename' ...前者甚至不會編譯。你的問題到底是什麼?你不知道如何將一個字符串傳遞給一個函數? – tnw

+0

'Comparer',你是否打算用'Compare'方法實現['IComparer'](http://msdn.microsoft.com/en-us/library/System.Collections.IComparer.aspx)接口?如果是這樣,沒有辦法改變進入它的參數的數量=/ – newfurniturey

回答

0
public static int Comparer(XmlElement a, XmlElwment b, string strAttributeName) 
+0

我認爲這是一個錯字 – Satpal

1

您試圖通過添加XML屬性名稱作爲參數使您的Comparer函數更通用。但是,這樣做會更改該功能的簽名,使其不再符合List.Sort(Comparison<T> comparison)所要求的代表的簽名。

幸運的是,您可以用一個lambda代替list.Sort(Comparer),它允許您將其他參數傳遞給函數Comparer。要通過"aa"作爲屬性名稱:

list.Sort((a, b) => Comparer(a, b, "aa")); 

通過"b"作爲屬性名稱:

list.Sort((a, b) => Comparer(a, b, "b")); 
0

你應該能夠做到以下幾點:

string strAttributeName = "aa"; //Or dynamically set the value 
list.Sort((a, b) => Comparer(a, b, strAttributeName)); 

此外,您將需要將您的Copare方法更正爲

public static int Comparer(System.Xml.XmlElement a, System.Xml.XmlElement b, 
    string strAttributeName) 

因爲「str」在C#中無效。