隐式转换为 Func 或 Action 委托?

Gle*_*den 6 c# delegates casting implicit func

C# 允许您定义对委托类型的隐式转换:

class myclass
{
    public static implicit operator Func<String, int>(myclass x)
    {
        return s => 5;
    }
    public static implicit operator myclass(Func<String, int> f)
    {
        return new myclass();
    }
}
Run Code Online (Sandbox Code Playgroud)

但不幸的是,我们不能使用它来使对象看起来像函数:

var xx = new myclass();
int j = xx("foo");    // error
Action<Func<String, int>> foo = arg => { };
foo(xx);              // ok
Run Code Online (Sandbox Code Playgroud)

有没有一种好方法可以使自己的类的对象直接在其基本实例上接受函数样式参数(参数)?有点像索引器,但用括号而不是方括号?

rea*_*kle 4

不可以,C# 不允许将其作为语言的一部分。在幕后,CLI 使用callcallvirt指令来调用方法或间接调用委托。

callable因此,与可以通过声明方法来创建类实例的 Python 不同def __call__,C# 没有类似的功能。

  • @GwynBleidd 是的,CLI 发生了一些变化,但核心概念不能改变,如 anwser 中提到的。另外,我认为我们不会在 C# 中看到此功能。 (2认同)