C# 4.0 可选参数 - 如何指定“Guid”类型的可选参数?

发布于 2024-09-12 22:12:54 字数 435 浏览 1 评论 0原文

这是我的方法:

public void SomeQuery(string email = "", Guid userId = Guid.Empty)
{
   // do some query
}

userId 给了我一个错误,因为它必须是一个编译时常量,这是我理解的。但即使我声明一个 const:

private const emptyGuid = Guid.Empty;

然后将方法签名更改为:

public void SomeQuery(string email = "", Guid userId = emptyGuid)
{
   // do some query
}

仍然没有爱。

我缺少什么?

Here's my method:

public void SomeQuery(string email = "", Guid userId = Guid.Empty)
{
   // do some query
}

userId is giving me an error as it must be a compile-time constant, which i understand. But even when i declare a const:

private const emptyGuid = Guid.Empty;

then change the method signature to:

public void SomeQuery(string email = "", Guid userId = emptyGuid)
{
   // do some query
}

still no love.

What am i missing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

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

发布评论

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

评论(3

背叛残局 2024-09-19 22:12:54

您是否尝试过将其设置为 Guid 的新实例 ala:

public void SomeQuery(string email = "", Guid userId = new Guid())
{
   // do some query
}

应该可以解决问题。

Have you tried setting it to a new instance of Guid ala:

public void SomeQuery(string email = "", Guid userId = new Guid())
{
   // do some query
}

Should do the trick.

囚我心虐我身 2024-09-19 22:12:54

更好的解决方案不是使用不需要 Guid 的版本来重载该方法吗?这将解决问题,并且在我看来将是更好的设计。当然,可能还有其他我不知道的限制需要这种设计。

Wouldn't a better solution be to overload the method with a version that doesn't require the Guid? This would solve the issue, and would be a better design in my opinion. Of course, there may be other constraints that I am unaware of necessitating this design.

睫毛上残留的泪 2024-09-19 22:12:54

也许它会有所帮助(使用运算符 ?? 和 Guid 可空类型)

public void some_method(string name, Guid? guid = null)
{
        _name = name;
        _guid = guid ?? Guid.NewGuid();
}

maybe it would help (using operator ?? and Guid nullable type)

public void some_method(string name, Guid? guid = null)
{
        _name = name;
        _guid = guid ?? Guid.NewGuid();
}
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文