C# 类型转换器和null
我正在使用一个类来存储连接字符串。我的应用程序从settings类中读取设置并将其分配给实例变量。然后将其绑定到某些控件。我的连接字符串类具有以下属性集:C# 类型转换器和null,c#,typeconverter,C#,Typeconverter,我正在使用一个类来存储连接字符串。我的应用程序从settings类中读取设置并将其分配给实例变量。然后将其绑定到某些控件。我的连接字符串类具有以下属性集: [TypeConverter(typeof(ConnectionStringConverter))] 我的类型转换器如下所示 问题是,如果设置文件中的设置为空,则设置类将返回null。而不是使用默认构造函数的连接字符串类的实例 请有人帮我解开这个谜 谢谢 public class ConnectionStringConverter : Ty
[TypeConverter(typeof(ConnectionStringConverter))]
我的类型转换器如下所示
问题是,如果设置文件中的设置为空,则设置类将返回null。而不是使用默认构造函数的连接字符串类的实例
请有人帮我解开这个谜
谢谢
public class ConnectionStringConverter : 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, CultureInfo culture, object value)
{
if (value is string)
return (ConnectionString)(value as string);
else
return base.ConvertFrom(context, culture, value);
}
public override object ConvertTo(ITypeDescriptorContext context, CultureInfo culture, object value, Type destinationType)
{
if (destinationType == typeof(string))
return (string)(value as ConnectionString);
else
return base.ConvertTo(context, culture, value, destinationType);
}
}
我认为问题在于:
public override object ConvertFrom(ITypeDescriptorContext context,
CultureInfo culture, object value)
{
// The first condition.
if (value is string)
return (ConnectionString)(value as string);
else
return base.ConvertFrom(context, culture, value);
}
让我们对条件语句进行分解:
if (value is string)
这很好,这是从字符串到ConnectionString
类的转换
return (ConnectionString)(value as string);
这就是问题所在。如果value
为空,则value as string
也为空,并且返回空引用
相反,您希望执行以下操作:
return (ConnectionString)(value as string) ?? new ConnectionString();
如果
value
为null,则将提供使用默认无参数构造函数调用的ConnectionString
类的实例。不要修复它。如果设置中没有连接字符串,那么就不可能自己创建一个有效的连接字符串。