C# 4.0 中使用动态类型的重载解析
我还无法访问 C# 4.0 预览版。 但我很好奇,在以下情况下调用重载方法时,C# 4.0 运行时会做什么。 它解析为通用重载...还是专用重载。
public class Foo<T>
{
protected string BarImpl( T value ) { return "Bar(T) says: " + value.ToString(); }
protected string BarImpl( int value ) { return "Bar(int) says: " + value.ToString(); }
public string Bar( T value )
{
dynamic foo = this;
return foo.BarImpl( value );
}
}
public static void Main( string args[] )
{
var f = new Foo<int>();
Console.WriteLine( f.Bar( 0 ) );
}
I don't have access to the C# 4.0 preview yet. But I am curious, what does the C# 4.0 runtime do when invoking an overloaded method in the following case. Does it resolve to the generic overload ... or the specialized overload.
public class Foo<T>
{
protected string BarImpl( T value ) { return "Bar(T) says: " + value.ToString(); }
protected string BarImpl( int value ) { return "Bar(int) says: " + value.ToString(); }
public string Bar( T value )
{
dynamic foo = this;
return foo.BarImpl( value );
}
}
public static void Main( string args[] )
{
var f = new Foo<int>();
Console.WriteLine( f.Bar( 0 ) );
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
一般来说,我的理解是,结果应该(只要可能)与使用只是将动态表达式替换为动态值所具有类型的表达式来编译相同的代码的结果相同在执行时。 (静态已知类型保留在调用站点信息中。)
在这种特殊情况下,仅使用 .NET 4.0b1 编写代码,结果是:
但是,再次查看此内容(并检查哪个位实际上是动态的)我我有点困惑。 我认为这是我必须非常仔细查看规范才能了解正确行为的情况之一。 不幸的是我不知道 C# 4.0 规范何时可用。
这是一个很难推理的问题,我怀疑关键部分是在执行时绑定器是否能够计算出相同
T
T 类型> 作为接收者,而不是类型int
。 因为在这种情况下接收器是动态的,所以编译器根本不执行任何重载解析。 唔。 绝对是棘手的一件事。In general, my understanding that the result should (whenever possible) be the same as the result would be if you compiled the same code with just the dynamic expressions replaced by expressions of the type that the dynamic value has at execution time. (Statically-known types are preserved in the call site info.)
In this particular case, having just your code with .NET 4.0b1, the result is:
However, having looked at this again (and checked which bit is actually dynamic) I'm slightly confused. I think it's one of those situations where I'd have to look very carefully at the spec to understand what the correct behaviour is. Unfortunately I don't know when the C# 4.0 spec will be available.
It's a tricky one to reason about, and I suspect the key part is whether at execution time the binder is able to work out that the value is of type
T
for the sameT
as the receiver, rather than typeint
. Because the receiver is dynamic in this case, the compiler doesn't do any overload resolution at all. Hmm. Tricky one, definitely.