XElement
厳密に型指定された方法で値をフェッチするための汎用メソッドを作成しようとしています。ここに私が持っているものがあります:
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);
}
}
}
First attempt
の行でわかるようにGetElementValue
、文字列 -> オブジェクト -> TElementType に移動しようとしています。残念ながら、これは整数のテスト ケースでは機能しません。次のテストを実行する場合:
[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.");
}
GetElementValue<int>
が呼び出されると、次の例外が発生します。
System.InvalidCastException : 要素値 '5' を型 'Int32' にキャストできません。
各キャスティング ケース (または少なくとも数値のケース) を個別に処理する必要がありますか?