首页 / C# / c# – 设置中的自定义类型
c# – 设置中的自定义类型
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了c# – 设置中的自定义类型,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含2051字,纯文字阅读大概需要3分钟。
内容图文
![c# – 设置中的自定义类型](/upload/InfoBanner/zyjiaocheng/801/c4488f60dfe141cb8b4e90be6ed9d995.jpg)
如何在“设置”中拥有自己的类型.
我成功将它们放在设置表中,但问题是我无法设置默认值.
问题是我无法在app.config中看到设置.
解决方法:
如果我正确解释你的问题,你有一个自定义类型,我们称之为CustomSetting,你可以在那个类型的Settings.settings文件中设置一个设置,并使用app.config或Visual Studio指定该设置的默认值设置UI.
如果这是你想要做的,你需要为你的类型提供一个可以从字符串转换的TypeConverter,如下所示:
[TypeConverter(typeof(CustomSettingConverter))]
public class CustomSetting
{
public string Foo { get; set; }
public string Bar { get; set; }
public override string ToString()
{
return string.Format("{0};{1}", Foo, Bar);
}
}
public class CustomSettingConverter : TypeConverter
{
public override bool CanConvertFrom(ITypeDescriptorContext context, Type sourceType)
{
if( sourceType == typeof(string) )
return true;
else
return base.CanConvertFrom(context, sourceType);
}
public override object ConvertFrom(ITypeDescriptorContext context, System.Globalization.CultureInfo culture, object value)
{
string stringValue = value as string;
if( stringValue != null )
{
// Obviously, using more robust parsing in production code is recommended.
string[] parts = stringValue.Split(';');
if( parts.Length == 2 )
return new CustomSetting() { Foo = parts[0], Bar = parts[1] };
else
throw new FormatException("Invalid format");
}
else
return base.ConvertFrom(context, culture, value);
}
}
一些背景资料
TypeConverter是.Net框架中许多字符串转换魔法的背后.它不仅对设置有用,它还是Windows窗体和组件设计者如何将值从属性网格转换为其目标类型,以及XAML如何转换属性值.许多框架的类型都有自定义TypeConverter类,包括所有基本类型,还有类似System.Drawing.Size或System.Windows.Thickness以及许多其他类型的类型.
从您自己的代码中使用TypeConverter非常简单,您只需要这样做:
TypeConverter converter = TypeDescriptor.GetConverter(typeof(TargetType));
if( converter != null && converter.CanConvertFrom(typeof(SourceType)) )
targetValue = (TargetType)converter.ConvertFrom(sourceValue);
支持哪些源类型各不相同,但字符串是最常见的类型.与普遍但不太灵活的Convert类(仅支持原始类型)相比,它是一种更强大的(并且遗憾的是鲜为人知)从字符串转换值的方法.
内容总结
以上是互联网集市为您收集整理的c# – 设置中的自定义类型全部内容,希望文章能够帮你解决c# – 设置中的自定义类型所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。