0

クラスを使用して接続文字列を格納しています。私のアプリは、設定クラスから設定を読み取り、それをインスタンス変数に割り当てます。これは、いくつかのコントロールにバインドされます。私の接続文字列クラスには、次の属性セットがあります。

[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);
    }
}
4

1 に答える 1

0

問題はここにあると思います:

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が null の場合はvalue as string、同様に null であり、null 参照を返しています。

代わりに、次のようにします。

return (ConnectionString)(value as string) ?? new ConnectionString();

valuenullのイベントでは、 coalesce オペレーターConnectionStringは、デフォルトのパラメーターなしのコンストラクターで呼び出されたクラスのインスタンスを提供します。

于 2012-07-18T17:02:30.727 に答える