[英]How to create an application settings parameter of type a custom struct (or class)?
有這個結構:
public struct MyStruct
{
public int MyInt { get; set; }
public bool MyBool { get; set; }
public string MyString { get; set; }
public MyStruct(int myint, bool mybool, string mystring)
{
MyInt = myint;
MyBool = mybool;
MyString = mystring;
}
}
如何在應用程序設置中存儲這種類型的值?
該類型在 select 的新參數列表中不可用,它的類型和瀏覽輸入完全限定的類型名稱不起作用,因為它沒有找到。
大多數教程和副本都不清楚,不完整,只提到類,很少提到結構。
主要來自這篇文章: Using Custom Classes with Application Settings
而各種搜索,我們需要添加Serializable和TypeConverter屬性:
[Serializable]
[TypeConverter(typeof(MyStructConverter))]
public struct MyStruct
{
public int MyInt { get; set; }
public bool MyBool { get; set; }
public string MyString { get; set; }
public MyStruct(int myint, bool mybool, string mystring)
{
MyInt = myint;
MyBool = mybool;
MyString = mystring;
}
}
這是類型轉換器 class:
public class MyStructConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
return sourceType == typeof(string) || base.CanConvertFrom(context, sourceType);
}
public override bool CanConvertTo(ITypeDescriptorContext context, Type destinationType)
{
return destinationType == typeof(string) || base.CanConvertTo(context, destinationType);
}
public override object ConvertFrom(ITypeDescriptorContext context, CultureInfo culture, object value)
{
if ( value is string )
{
string[] parts = ( (string)value ).Split(new char[] { ';' });
var instance = new MyStruct();
instance.MyInt = parts.Length > 0 ? Convert.ToInt32(parts[0]) : 0;
instance.MyBool = parts.Length > 1 ? Convert.ToBoolean(parts[1]) : false;
instance.MyString = parts.Length > 2 ? Convert.ToString(parts[2]) : "";
return instance;
}
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if ( destinationType == typeof(string) )
{
var instance = (MyStruct)value;
return string.Format("{0};{1};{2}", instance.MyInt, instance.MyBool, instance.MyString);
}
return base.ConvertTo(context, culture, value, destinationType);
}
}
接下來我們需要編譯項目。
現在我們可以添加參數並選擇它的類型:
或者如果列表中沒有可用的底部菜單項Browse來輸入完全限定的類型名稱:
為了能夠寫:
var myParam = Properties.Settings.Default.MyParam;
myParam.MyInt = 10;
myParam.MyBool = true;
myParam.MyString = "Test";
Properties.Settings.Default.MyParam = myParam;
Properties.Settings.Default.Save();
必需的命名空間:
using System;
using System.ComponentModel;
using System.Globalization;
結果:
<?xml version="1.0" encoding="utf-8"?>
<configuration>
<userSettings>
<WindowsFormsAppTest.Properties.Settings>
<setting name="MyParam" serializeAs="String">
<value>10;True;Test</value>
</setting>
</WindowsFormsAppTest.Properties.Settings>
</userSettings>
</configuration>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.