C#"常量对象"作为默认参数使用 [英] C# "Constant Objects" to use as default parameters

查看:135
本文介绍了C#"常量对象"作为默认参数使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有什么办法来创建一个常量对象(即它不能被编辑,并在编译时创建的)?

Is there any way to create a constant object(ie it cannot be edited and is created at compile time)?

我只是用C#语言玩耍,注意到可选参数功能,并认为这可能是整齐,以便能够使用默认的对象作为一个可选的参数。考虑以下几点:

I am just playing with the C# language and noticed the optional parameter feature and thought it might be neat to be able to use a default object as an optional parameter. Consider the following:

//this class has default settings
private const SettingsClass DefaultSettings = new SettingsClass ();

public void doSomething(SettingsClass settings = DefaultSettings)
{

}

这显然不编译,但我想做些什么的例子。
是否有可能创建一个常量对象这样的,并用它作为默认的一个可选的参数??

This obviously does not compile, but is an example of what I would like to do. Would it be possible to create a constant object like this and use it as the default for an optional parameter??

推荐答案

没有,可选参数的默认值都必须编译时间常数。

No, default values for optional parameters are required to be compile-time constants.

在你的情况下,解决方法是:

In your case, a workaround would be:

public void doSomething(SettingsClass settings = null)
{
    settings = settings ?? DefaultSettings;
    ...
}

这篇关于C#"常量对象"作为默认参数使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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