English 中文(简体)
自定义设置提供和检索默认值
原标题:Custom SettingsProvider and retrieving default value

我已经实现了自己的类,该类继承自SettingsProvider类。如果用户没有设置我正在检索的值,即这是程序第一次启动,我会尝试获取默认值。我看到的问题是,当从SettingsProperty检索默认值时,它会以字符串的形式返回。我试图添加一些转换该项的代码,但在转换System.Drawing.Colors时遇到问题,并且收到错误“从System.String到System.Drawing.Color的强制转换无效”。

以下是我用来获取默认值的代码示例:

 private object GetDefaultValue(SettingsProperty setting)
  {
         if (setting.PropertyType.IsEnum)
             return Enum.Parse(setting.PropertyType, setting.DefaultValue.ToString());

        // Return the default value if it is set
        if (setting.DefaultValue != null)
           return Convert.ChangeType(setting.DefaultValue, setting.PropertyType);
        else // If there is no default value return the default object
           return Activator.CreateInstance(setting.PropertyType);
   }

如何将默认值正确转换为正确的类型?

最佳回答

好的。所以我找到了答案。您不需要使用Convert.ChangeType,而是需要根据settings.PropertyType实际创建一个TypeConverter实例。此代码适用于:

private object GetDefaultValue(SettingsProperty setting)
  {
         if (setting.PropertyType.IsEnum)
             return Enum.Parse(setting.PropertyType, setting.DefaultValue.ToString());

        // Return the default value if it is set
        // Return the default value if it is set
         if (setting.DefaultValue != null)
         {
             System.ComponentModel.TypeConverter tc = System.ComponentModel.TypeDescriptor.GetConverter(setting.PropertyType);
             return tc.ConvertFromString(setting.DefaultValue.ToString());
         }
         else // If there is no default value return the default object
         {
             return Activator.CreateInstance(setting.PropertyType);
         }
   }
问题回答

暂无回答




相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签