tôi viết dưới đây phương pháp với follwing yêu cầu -phương pháp Generic trở Nullable Loại giá trị
- đầu vào là XmlNode và AttributeName
- trở lại giá trị nếu nó được tìm thấy với tên thuộc tính liên quan đến thông qua
Trường hợp không có giá trị trong attributeName được chuyển, nó sẽ trả về -
3.1. Đối với int -1 3.2. Đối với ngày giờ DateTime.MinValue 3.3. Đối với chuỗi, null 3.4. Đối với bool, null
Phương pháp dưới đây không thành công cho trường hợp 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));
}
Khi thay đổi này để
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));
}
Nó không cho loại chuỗi ví dụ: trường hợp 3,3
Mong cho một số giúp đỡ.
Làm thế nào để bạn _call_ phương pháp trong bộ mã đầu tiên của bạn? Bạn cần gọi nó là 'AttributeValue (...) 'Nếu bạn chỉ cần gọi' AttributeValue (...) 'thì' null' không phải là giá trị hợp lệ cho 'bool'. EDIT: Và trường hợp thứ hai của bạn thất bại vì 'string' không thể được sử dụng cho' System.Nullable 'vì' string' không phải là một struct kiểu giá trị. –