Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/csharp/286.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 类型转换器和null_C#_Typeconverter - Fatal编程技术网

C# 类型转换器和null

C# 类型转换器和null,c#,typeconverter,C#,Typeconverter,我正在使用一个类来存储连接字符串。我的应用程序从settings类中读取设置并将其分配给实例变量。然后将其绑定到某些控件。我的连接字符串类具有以下属性集: [TypeConverter(typeof(ConnectionStringConverter))] 我的类型转换器如下所示 问题是,如果设置文件中的设置为空,则设置类将返回null。而不是使用默认构造函数的连接字符串类的实例 请有人帮我解开这个谜 谢谢 public class ConnectionStringConverter : Ty

我正在使用一个类来存储连接字符串。我的应用程序从settings类中读取设置并将其分配给实例变量。然后将其绑定到某些控件。我的连接字符串类具有以下属性集:

[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
类的实例。

不要修复它。如果设置中没有连接字符串,那么就不可能自己创建一个有效的连接字符串。