第一个问题:
在 PHP 中有:
$b = new SomeClass();
$a = "foo";
$b->$a("something"); // This is the same as $b->foo("something");
如何在 C# 中执行此操作?
第二个问题:
在 PHP 中,我可以遍历类中的每个方法,类似于:
$a = new SomeClass(); // Which implements methodA, methodB;
foreach($method in get_class_methods(SomeClass()))
{
$method("do stuff with each method");
}
如何在 C# 中执行此操作?
第三个问题
PHP 有一个神奇的方法 __call()
如果一个类没有实现它作为默认方法执行它,例如如果一个方法不存在它仍然可以运行
class NewClass()
{
// constructor
__call(class name, array of parameters)
{
}
}
所以如果你这样做
$a = new NewClass();
$a->thisDoesntExistButWorks("123","abc");
// The method gets "magically created" such as
thisDoesntExistButWorks(array with 123 and abc)....
最佳答案
您的 PHP 功能没有一个可以在 C# 中优雅地实现,但除了第三个功能外,它们都是可能的。
1:
var b = new SomeClass();
var a = "Foo";
b.GetType().GetMethod(a).Invoke(b, /*object[] of parameters*/);
2:
var a = new SomeClass();
foreach(MethodInfo mi in a.GetType.GetMethods())
{
/*do something with method using mi*/
}
您可以在 3.5 中实现一个扩展方法 ForEach()(可能在 4.0 的 Linq 库中可用),将其变成一个方法链;大括号中的代码将成为 lambda。
据我所知,#3 在 C# 中以任何内置方式都是不可能的。您可以通过尝试在 try block 中以反射方式调用该方法、捕获调用失败时抛出的任何 TargetExceptions 并在捕获中实现您的默认行为来解决它。
关于c# - 如何在 C# 中从 PHP 执行这 3 个操作(moSTLy 自省(introspection)),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3841117/