<分区>
在调查 C# 动态关键字的工作原理时,我偶然发现了一些奇怪的行为。它几乎看起来像一个错误,但更有可能是该行为的原因。
在下面的代码中,有两个调用,一个调用 obj1,一个调用 obj2,但只有一个调用正确执行。看起来局部变量类型是原因,但“Hello”也应该可以从 IDynamicTarget 访问,因为它扩展了 IDynamicTargetBase。
namespace DynamicTesting
{
interface IDynamicTargetBase
{
string Hello(int a);
}
interface IDynamicTarget : IDynamicTargetBase
{
}
class DynamicTarget : IDynamicTarget
{
public string Hello(int a)
{
return "Hello!";
}
}
class Program
{
static void Main(string[] args)
{
dynamic a = 123;
IDynamicTargetBase obj1 = new DynamicTarget();
obj1.Hello(a); // This works just fine
IDynamicTarget obj2 = new DynamicTarget();
obj2.Hello(a); // RuntimeBinderException "No overload for method 'Hello' takes '1' arguments"
}
}
}