C#4.0:我可以用一个时间跨度为具有默认值的可选参数? [英] C# 4.0: Can I use a TimeSpan as an optional parameter with a default value?

查看:284
本文介绍了C#4.0:我可以用一个时间跨度为具有默认值的可选参数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这两个产生一个错误,说他们一定是一个编译时间常数:

Both of these generate an error saying they must be a compile-time constant:

void Foo(TimeSpan span = TimeSpan.FromSeconds(2.0))
void Foo(TimeSpan span = new TimeSpan(2000))

首先,有人可以解释为什么这些价值不能在编译时确定的?而是否有一个可选的TimeSpan对象指定一个默认值的方法吗?

First of all, can someone explain why these values can't be determined at compile time? And is there a way to specify a default value for an optional TimeSpan object?

推荐答案

您可以通过更改您的签名解决这个非常容易。

You can work around this very easily by changing your signature.

void Foo(TimeSpan? span = null) {

   if (span == null) { span = TimeSpan.FromSeconds(2); }

   ...

}

我要阐述 - 在你的榜样这些前pressions不是编译时常是因为在编译时,编译器不能简单地执行TimeSpan.FromSeconds(2.0)的原因,并坚持结果的字节到你的编译code。

I should elaborate - the reason those expressions in your example are not compile-time constants is because at compile time, the compiler can't simply execute TimeSpan.FromSeconds(2.0) and stick the bytes of the result into your compiled code.

作为一个例子,考虑如果你试图改用DateTime.Now。 DateTime.Now的价值变化,每它的执行时间。或者,假设TimeSpan.FromSeconds考虑到重力。这是一个荒谬的例子,但只是因为我们碰巧知道TimeSpan.FromSeconds是确定性的编译时间常数的规则不作特殊情况。

As an example, consider if you tried to use DateTime.Now instead. The value of DateTime.Now changes every time it's executed. Or suppose that TimeSpan.FromSeconds took into account gravity. It's an absurd example but the rules of compile-time constants don't make special cases just because we happen to know that TimeSpan.FromSeconds is deterministic.

这篇关于C#4.0:我可以用一个时间跨度为具有默认值的可选参数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆