I wrote below method with follwing requirement -
- 输入的是xmlnode和attributeName
- 如果找到与传递的关联属性名称相关联的值,则返回该值
如果传递的 attributeName 中没有值,它应该返回 -
3.1。对于整数 -1 3.2.对于日期时间 DateTime.MinValue 3.3.对于字符串,空 3.4.对于 bool,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));
}
It fails for string type i.e. case 3.3
期待一些帮助。
最佳答案
对于 3.4,您需要使用 bool?
作为 T 的类型,这样您就可以返回 null。
然后你可以为 3.3 和 3.4(string 和 bool?)使用 default
关键字。根据 msdn它将为引用类型返回 null
并为值类型(如 int 或 bool)返回默认值。
你可以这样使用它
return default(T);
关于c# - 返回可空类型值的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17363937/