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)
有没有一种好方法可以使自己的类的对象直接在其基本实例上接受函数样式参数(参数)?有点像索引器,但用括号而不是方括号?
不可以,C# 不允许将其作为语言的一部分。在幕后,CLI 使用call和callvirt指令来调用方法或间接调用委托。
callable因此,与可以通过声明方法来创建类实例的 Python 不同def __call__,C# 没有类似的功能。