C# “Constant Objects” to use as default parameters

浪子不回头ぞ 提交于 2019-12-04 15:54:21

问题


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

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??


回答1:


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;
    ...
}



回答2:


Generally what you want is not possible. You can fake it with an "invalid" default value as Ani's answer shows, but this breaks down if there is no value you can consider invalid. This won't be a problem with value types where you can change the parameter to a nullable type, but then you will incur boxing and may also "dilute" the interface of the function just to accommodate an implementation detail.

You can achieve the desired functionality if you replace the optional parameter with the pre-C# 4 paradigm of multiple overloads:

public void doSomething()
{
    var settings = // get your settings here any way you like
    this.doSomething(settings);
}

public void doSomething(SettingsClass settings)
{
    // implementation
}

This works even if the parameter is a value type.




回答3:


You could use the readonly attribute, instead of const. For example:

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

public void doSomething(SettingsClass settings = DefaultSettings) 
{ 
} 


来源:https://stackoverflow.com/questions/5372600/c-sharp-constant-objects-to-use-as-default-parameters

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!