いくつかの .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; }