我正在使用Visual Studio v12.0并查看解决方案资源管理器中的Settings.Designer.cs文件。在Properties命名空间中,Settings派生类是从ApplicationSettingsBase类创建的,如下所示:
internal sealed partial class Settings : global::System.Configuration.ApplicationSettingsBase
在课堂上,这行代码让我困惑:
private static Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
我相信这是一个向下倾斜的例子。我不清楚为什么这是必要的。为什么不创建一个Settings实例,因为它已被定义为继承基础?
这是一个更长的代码段:
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...
}
答案 0 :(得分:1)
行:
Settings defaultInstance = ((Settings)(global::System.Configuration.ApplicationSettingsBase.Synchronized(new Settings())));
相当于说:
Settings s1 = new Settings();
SettingsBase synchronizedBaseSettings = global::System.Configuration.ApplicationSettingsBase.Synchronized(s1);
Settings settings = (Settings)synchronizedBaseSettings;
所以强制转换是必需的,因为ApplicationSettingsBase.Synchronized
会返回SettingsBase
类型。并且ApplicationSettingsBase.Synchronized
被调用以使设置对象线程安全。否则,您必须:a)将defaultInstance
定义为SettingsBase
或b)不要调用ApplicationSettingsBase.Synchronized
并冒险线程问题。
我想现在方法ApplicationSettingsBase.Synchronized
将被声明为这样的通用:
public static TSettings Synchronized<TSettings> (TSettings settingsBase) where TSettings: SettingsBase
但是这个类可能比c#中的泛型更早。)。