1

我正在将一些 .NET 1.1 代码重构为更易于维护的 .NET 4.0 代码,并了解对代码进行全面检修的效果。

当前代码的很大一部分依赖于HashTable实例,这些实例基本上是一种属性包,包含简单值类型的值,如 int/double/single 和 string。

周围是大量的复制/粘贴代码进行转换,其中相当多的地方是“几乎”包含错误的副本。

因此,我对LoadValue如下功能的计划。

应用程序中的逻辑假定字符串永远不会为空,并且总是被修剪。
在我下面的方法中,基于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.Stringsealed,表达式

genericType.IsSubclassOf(stringType)

是相同的

genericType==stringType

因此,您不需要调用Convert.ChangeType: 您可以T通过转换为 来转换object,如下所示:

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 回答