Выражение NewLanguageFeatures-lambda использует значение n - PullRequest
0 голосов
/ 10 мая 2011

Я разбирался с понятиями лямбда-выражения и методов расширения: -

namespace NewLanguageFeatures
{ 
public delegate bool KeyValuePair<K, V>(K key, V value);  
/// <summary>
/// Task 13 – Calling a Complex Extension Method using Lambda Expressions [ops]
/// </summary>
public static class LambdaExtensions
{
    //This extension method takes in a dictionary and a delegate
    public static List<K> FilterBy<K, V>(
    this Dictionary<K, V> items,
    KeyValueFilter<K, V> filter)
    {
        var result = new List<K>();
        foreach (KeyValuePair<K, V> element in items)
        {
            if (filter(element.Key, element.Value))
                result.Add(element.Key);
        }
        return result;
    }
}
}

дает следующую ошибку:

Error     1 Cannot convert type 'System.Collections.Generic.KeyValuePair<K,V>' to 'NewLanguageFeatures.KeyValuePair<K,V>'   and

Error  2    'NewLanguageFeatures.KeyValuePair<K,V>' does not contain a definition for 'Key' and no extension method 'Key' accepting a first argument of type 'NewLanguageFeatures.KeyValuePair<K,V>' could be found (are you missing a using directive or an assembly reference?)   

есть идеи для восстановления?

1 Ответ

0 голосов
/ 10 мая 2011

Это просто опечатка в вашем коде:

public delegate bool KeyValuePair<K, V>(K key, V value);  

обязательно должно быть

public delegate bool KeyValueFilter<K, V>(K key, V value);  

и тогда это работает.

Однако, Func<K,V,bool> будет делать то же самое, без необходимости дополнительного определения. Наконец, использование var (т.е. foreach(var element in items) позволило бы избежать одного из конфликтов.

Честно говоря, существующий Where делает столько этого, что я бы не стал его определять - т.е.

var filtered = existing.Where(pair => pair.Key == pair.Value);
           // ^^^ just a random filter to show usage; nothing significant here
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...