我写了下面的方法与follwing要求 -返回可空类型通用的方法值
- 输入的XMLNode和的attributeName
- 回报,一旦发现与传递 相关的属性名称值
如果在传递的attributeName中没有值,则应返回 -
3.1。对于int -1 3.2。对于日期时间DateTime.MinValue 3.3。对于字符串,null 3.4。对于布尔,null
下面的方法在案例3.4中失败。
public T AttributeValue<T>(XmlNode node, string attributeName)
{
var value = new object();
if (node.Attributes[attributeName] != null && !string.IsNullOrEmpty(node.Attributes[attributeName].Value))
{
value = node.Attributes[attributeName].Value;
}
else
{
if (typeof(T) == typeof(int))
value = -1;
else if (typeof(T) == typeof(DateTime))
value = DateTime.MinValue;
else if (typeof(T) == typeof(string))
value = null;
else if (typeof(T) == typeof(bool))
value = null;
}
return (T)Convert.ChangeType(value, typeof(T));
}
当改变这
public System.Nullable<T> AttributeValue<T>(XmlNode node, string attributeName) where T : struct
{
var value = new object();
if (node.Attributes[attributeName] != null && !string.IsNullOrEmpty(node.Attributes[attributeName].Value))
{
value = node.Attributes[attributeName].Value;
}
else
{
if (typeof(T) == typeof(int))
value = -1;
else if (typeof(T) == typeof(DateTime))
value = DateTime.MinValue;
else if (typeof(T) == typeof(string))
return null;
else if (typeof(T) == typeof(bool))
return null;
}
return (T?)Convert.ChangeType(value, typeof(T));
}
它无法为字符串类型,即3.3的情况下
期待一些帮助。
你如何_call_在你的第一套代码中的方法?您需要将它称为'AttributeValue(...)'如果您只是调用'AttributeValue (...)',那么'null'不是'bool'的有效值。编辑:而你的第二种情况失败,因为'字符串'不能用于'System.Nullable '因为'字符串'不是一个值类型的结构。 –