1

いくつかの .NET 1.1 コードをリファクタリングして、もう少し保守しやすい .NET 4.0 コードにしようとしているところです。コードを完全に見直すとどうなるかを感じ取っています。

現在のコードの大部分は、基本的に int/double/single や string などの単純な値型の値を含む一種のプロパティ バッグであるHashTableインスタンスに依存しています。

その周りには、ほとんどが変換を行うコピー/貼り付けコードの巨大なチャンクがあり、それらの場所のかなりの数は、バグを含む「ほぼ」コピーです。

LoadValueしたがって、以下のような関数の私の計画。

アプリケーションのロジックは、文字列が null になることはなく、常にトリミングされることを前提としています。以下の私の方法では、 Convert.ChangeType
に基づいており、これに対する解決策は「不器用」に感じられるため、次のようになります。

  • これを行うための不器用な方法はありますか?
  • この方法で明らかなことを見落としていますか?

    /// <summary>
    /// Centralize all the null/value behaviour for converting properties in bags to business object properties.
    /// </summary>
    /// <typeparam name="T">type to get; can be simple value type (int, double, etc) or string</typeparam>
    /// <param name="properties">HashTable to get property from</param>
    /// <param name="propertyName">name of property to get</param>
    /// <returns>default(T) if property does not have value, otherwise Trimmed value for string, or value for other types.</returns>
    protected T LoadValue<T>(Hashtable properties, string propertyName)
    {
        T result;
        bool haveValue = properties[propertyName] != null;
        Type genericType = typeof(T);
        Type stringType = typeof(string);
        if (genericType.IsSubclassOf(stringType))
        {
            string stringResult;
            if (haveValue)
                stringResult = ((string)properties[propertyName]).Trim();
            else
                stringResult = string.Empty;
            result = (T)Convert.ChangeType(stringResult, genericType); //(T)(stringResult);
        }
        else
        {
            if (haveValue)
                result = ((T)properties[propertyName]);
            else
                result = default(T);
        }
        return result;
    }
    
4

1 に答える 1

1

System.Stringであるためsealed、式

genericType.IsSubclassOf(stringType)

と同じです

genericType==stringType

したがって、 の呼び出しは必要ありません。次のように にキャストConvert.ChangeTypeすることで にキャストできます。Tobject

object stringResult; // Note the change of type to "object"
if (haveValue)
    stringResult = ((string)properties[propertyName]).Trim();
else
    stringResult = string.Empty;
result = (T)stringResult; // It is allowed to cast object to generic T
于 2013-03-01T12:23:24.477 に答える