C# 4.0 中使用动态类型的重载解析

发布于 2024-07-23 08:21:07 字数 524 浏览 3 评论 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

没有你我更好 2024-07-30 08:21:07

一般来说,我的理解是,结果应该(只要可能)与使用只是将动态表达式替换为动态值所具有类型的表达式来编译相同的代码的结果相同在执行时。 (静态已知类型保留在调用站点信息中。)

在这种特殊情况下,仅使用 .NET 4.0b1 编写代码,结果是:

Bar(int) says: 0

但是,再次查看此内容(并检查哪个位实际上是动态的)我我有点困惑。 我认为这是我必须非常仔细查看规范才能了解正确行为的情况之一。 不幸的是我不知道 C# 4.0 规范何时可用。

这是一个很难推理的问题,我怀疑关键部分是在执行时绑定器是否能够计算出相同 TT 类型> 作为接收者,而不是类型 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:

Bar(int) says: 0

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 same T as the receiver, rather than type int. Because the receiver is dynamic in this case, the compiler doesn't do any overload resolution at all. Hmm. Tricky one, definitely.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文