Tôi đang cố gắng viết một phương pháp chung để tìm giá trị XElement
theo kiểu được đánh máy mạnh. Dưới đây là những gì tôi có:Cách truyền sang tham số chung trong C#?
public static class XElementExtensions
{
public static XElement GetElement(this XElement xElement, string elementName)
{
// Calls xElement.Element(elementName) and returns that xElement (with some validation).
}
public static TElementType GetElementValue<TElementType>(this XElement xElement, string elementName)
{
XElement element = GetElement(xElement, elementName);
try
{
return (TElementType)((object) element.Value); // First attempt.
}
catch (InvalidCastException originalException)
{
string exceptionMessage = string.Format("Cannot cast element value '{0}' to type '{1}'.", element.Value,
typeof(TElementType).Name);
throw new InvalidCastException(exceptionMessage, originalException);
}
}
}
Như bạn có thể nhìn thấy trên đường First attempt
của GetElementValue
, tôi đang cố gắng để đi từ chuỗi -> đối tượng -> TElementType. Thật không may, điều này không làm việc cho một trường hợp thử nghiệm số nguyên. Khi chạy thử nghiệm sau đây:
[Test]
public void GetElementValueShouldReturnValueOfIntegerElementAsInteger()
{
const int expectedValue = 5;
const string elementName = "intProp";
var xElement = new XElement("name");
var integerElement = new XElement(elementName) { Value = expectedValue.ToString() };
xElement.Add(integerElement);
int value = XElementExtensions.GetElementValue<int>(xElement, elementName);
Assert.AreEqual(expectedValue, value, "Expected integer value was not returned from element.");
}
tôi nhận được ngoại lệ sau khi GetElementValue<int>
được gọi là:
System.InvalidCastException : Cannot cast element value '5' to type 'Int32'.
Tôi sẽ phải xử lý từng trường hợp đúc (hoặc ít nhất là những số) riêng biệt?
Điều này phù hợp với tôi. 'ChangeType' trả về một đối tượng vẫn còn, nhưng hàm cast ngầm hiện hoạt động. Ngoài ra, bây giờ tôi kiểm tra 'FormatException' thay vì' InvalidCastException' trong khối 'try/catch'. Câu trả lời ngắn và đơn giản. – Scott
Sau khi điều tra thêm, bạn không thể sử dụng điều này với các loại nullable. Vì vậy, bằng cách sử dụng bài viết này: http://aspalliance.com/852 Tôi đã viết một phương pháp mở rộng để xử lý cả hai loại. – Scott