有什么方法可以在方法上调用扩展方法,但没有显式引用?
例如,如果我有一个扩展方法:
public static class Extensions {
public static void FooOn(this Func<string> method) =>
Console.WriteLine($"Foo on {method()}");
}
我以为也许我可以做这样的事情,但也许不能。
class Program {
private string Bar() => "you";
void Main() => Bar.FooOn(); // won't compile
}
相反,似乎我必须声明一个临时引用:
class Program {
private string Bar() => "you";
void Main(){
Func<string> temp = Bar;
temp.FooOn();
}
}
那么,有什么方法可以在没有显式引用的情况下调用方法的扩展方法?
不,您不能,因为它是方法,不能与扩展方法一起使用。
有几种解决方法(.NET Fiddle):
Func<string> temp = Bar;
temp.FooOn();
Bar
转换为Func<string>
:static void Main() => ((Func<string>)Bar).FooOn();
Bar
作为参数传递扩展方法:static void Main() => Extensions.FooOn(Bar);
Bar
为Func<string>
变量:static Func<string> Bar = () => "you";
static void Main() => Bar.FooOn();
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句