我有幾種方法,而且還在不斷擴展。所以,我打算讓它通用。誰能幫我解決這個問題。至少方法定義。
private static Dictionary<string, class1> PToDictionary(MapField<string, class1Proto> keyValuePairs)
{
Dictionary<string, class1> keyValues = new();
foreach (var pair in keyValuePairs)
{
**keyValues[pair.Key] = pToR(pair.Value);**
}
return keyValues;
}
我的另一種方法是:
private static Dictionary<Uri, class2> PToDictionary1(MapField<string, class2Proto> keyValuePairs)
{
Dictionary<string, class2> keyValues = new();
foreach (var pair in keyValuePairs)
{
**keyValues[new Uri(pair.Key)] = pToR1(pair.Value);**
}
return keyValues;
}
我怎樣才能使這個通用,以便在添加更多方法時,我不需要添加代碼。我在想這樣的事情,但錯誤是:
// Not sure how to call this method after Func is there
private static Dictionary<TKey, TValue> PToDictionary<TKey, TValue, TKeyProto, TValueProto>(MapField<TKeyProto, TValueProto> keyValuePairs, Func<TKeyProto, TKey> keyFunc, Func<TValueProto, TValue> valueFunc)
{
//How can I generalize my above method ?
}
有人可以幫我完成這個方法嗎?
uj5u.com熱心網友回復:
你根本不需要額外的方法。LINQ 已經提供了您需要的一切,并結合了MapField實作IDictionary<TKey, TValue>(因此IEnumerable<KeyValuePair<TKey, TValue>>.
您只需致電:
var dictionary = repeatedField.ToDictionary(
pair => ConvertKey(pair.Key), pair => ConvertValue(pair.Value));
(ConvertKey您想要將重復欄位鍵轉換為字典鍵的任何代碼在哪里,對于 也是如此ConvertValue)。
示例呼叫:
var d1 = repeatedField1.ToDictionary(pair => pair.Key, pair => pToR(pair.Value));
var d2 = repeatedField2.ToDictionary(
pair => new Uri(pair.Key), pair => pToR1(pair.Value));
...但無論如何您都可以洗掉pToRand方法。pToR1(如果沒有關于他們在做什么的資訊,很難判斷......)
uj5u.com熱心網友回復:
您可以使用以下方法轉換MapField<TKeyProto, TValueProto>為Dictionary<TKey, TValue>:
public static Dictionary<TKey, TValue> PToDictionary<TKey, TValue, TKeyProto, TValueProto>(
MapField<TKeyProto, TValueProto> keyValuePairs,
Func<TKeyProto, TKey> mapKey,
Func<TValueProto, TValue> mapValue
)
{
Dictionary<TKey, TValue> keyValues = new();
foreach (var pair in keyValuePairs)
{
keyValues[mapKey(pair.Key)] = mapValue(pair.Value);
}
return keyValues;
}
這里,mapKey是將MapField's 的鍵轉換為字典鍵的函式。同樣,mapValue將MapField' 值轉換為字典值。
另一種方法是使用 LINQ ToDictionary擴展方法:
public static Dictionary<TKey, TValue> PToDictionary<TKey, TValue, TKeyProto, TValueProto>(
MapField<TKeyProto, TValueProto> keyValuePairs,
Func<TKeyProto, TKey> mapKey,
Func<TValueProto, TValue> mapValue
)
{
// this is possible because MapField<TKey, TValue> implements IEnumerable<KeyValuePair<TKey, TValue>>
return keyValuePairs.ToDictionary(
(KeyValuePair<TKeyProto, TValueProto> kvp) => mapKey(kvp.Key),
(KeyValuePair<TKeyProto, TValueProto> kvp) => mapValue(kvp.Value));
}
例如,如果要轉換MapField<string, string>為Dictionary<Uri, int>可以使用以下代碼:
Dictionary<Uri, int> dictionary = PToDictionary(
map,
key => new Uri(key),
val => int.Parse(val));
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/449177.html
上一篇:從通用容器類中對通用串列進行排序
