简体   繁体   中英

Downcasting in Settings Class - Visual Studio

I'm using Visual Studio v12.0 and looking at the Settings.Designer.cs file in the Solution Explorer. In the Properties namespace, the Settings derived class is created from ApplicationSettingsBase class like so:

internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase

In the class, this line of code has me confused:

private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

This is an example of downcasting, I believe. I'm not clear why this is necessary. Why not just create an instance of Settings since it's already defined as inheriting the base?

Here's a longer snippet:

namespace ConfigMgrTest.Properties {

[global::System.Runtime.CompilerServices.CompilerGeneratedAttribute()]
[global::System.CodeDom.Compiler.GeneratedCodeAttribute("Microsoft.VisualStudio.Editors.SettingsDesigner.SettingsSingleFileGenerator", "12.0.0.0")]
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase {

    private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

    public static Settings Default {
        get {   
            return defaultInstance;
        }
    }

...rest of the namespace...

}

the line:

Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));

is equivalent to saying:

Settings s1 = new Settings();
SettingsBase synchronizedBaseSettings = global::System.Configuration.ApplicationSettingsBase.Synchronized(s1);
Settings settings = (Settings)synchronizedBaseSettings;

So the cast is required because ApplicationSettingsBase.Synchronized returns SettingsBase type. And ApplicationSettingsBase.Synchronized is called to make the settings object threadsafe. Otherwise you would have to: a) define defaultInstance as SettingsBase or b) do not call ApplicationSettingsBase.Synchronized and risk threading issues.

I guess nowadays the method ApplicationSettingsBase.Synchronized would be declared as a generic like this:

public static TSettings Synchronized<TSettings> (TSettings settingsBase) where TSettings: SettingsBase

But this class is probably older than generics in c# ;).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM