方法组的C#扩展方法 [英] C# extension method for a method group

查看:62
本文介绍了方法组的C#扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想为方法实现扩展方法.考虑以下代码示例( http://dotnetfiddle.net/HztiOo ):

I want to implement an extension method for a method. Consider the following code sample (http://dotnetfiddle.net/HztiOo) :

using System;
using System.Collections.Generic;

public class Program
{
    public static void Main()
    {
        A a = new A();
        // Noticed that Next() is called twice
        Console.WriteLine(a.Next(1));
        Console.WriteLine(a.Next(1));

        // Works
        var withCache = ((Func<int,int>)a.Next).AddCaching();
        withCache = new Func<int,int>(a.Next).AddCaching();
        withCache = ExtensionMethods.AddCaching<int,int>(a.Next);

        // Doesn't work :(
        // withCache = a.Next.AddCaching<int,int>();
        // Func<int,int> withCache = a.Next.AddCaching();

        // Notice that Next() is only called once
        Console.WriteLine(withCache(1));
        Console.WriteLine(withCache(1));
    }
}

public class A
{
    public int Next(int n)
    {
        Console.WriteLine("Called Next("+n+")");
        return n + 1;
    }
}

public static class ExtensionMethods
{
    public static Func<TKey,TVal> AddCaching<TKey,TVal>(this Func<TKey,TVal> fetcher)
    {
        var cache = new Dictionary<TKey, TVal>();
        return k =>
        {
            if (!cache.ContainsKey(k)) cache[k] = fetcher(k);
            return cache[k];
        };
    }
}

我希望能够在没有显式强制转换的情况下调用扩展方法.在上述两个无效"示例中,类型系统都应该能够自行找出要使用的重载...

I would like to be able to call the extension method without an explicit cast. In both "doesn't work" examples above, the type system should be able to figure out which overload to use on its own...

为什么我不能只使用a.Next.AddCaching<int,int>()?

注意:这只是一个例子,我不讨论讨论将高速缓存添加到方法调用的最佳方法,因为这种扩展还有很多其他可能性.

Note: this is just an example, I am not interested in discussing the best way to add a cache to a method invocation, as there are many other possibilities for this kind of extensions.

推荐答案

根据埃里克·利珀特博客方法组是无类型的表达式.而且您什么也做不了,只需处理它即可.

According to Eric Lippert blog method group is typeless expression. And you can't do anything, just deal with it.

这就是为什么您不能将其隐式转换为特定委托并向其添加扩展方法的确切原因

That's exact reason why you can't implicitly cast it to specific delegate and add extension method to it

这篇关于方法组的C#扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆