मैं दृढ़ता से टाइप किए गए फैशन में XElement
मान लाने के लिए एक सामान्य विधि लिखने की कोशिश कर रहा हूं। यहाँ मैं क्या है: आप GetElementValue
की First attempt
लाइन पर देख सकते हैं, मैं स्ट्रिंग से जाने के लिए कोशिश कर रहा हूँसी # में जेनेरिक पैरामीटर कास्ट कैसे करें?
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);
}
}
}
-> वस्तु -> 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 : Cannot cast element value '5' to type 'Int32'.
मैं (या कम से सांख्यिक लोगों पर) प्रत्येक कास्टिंग मामले को संभालने के लिए करने जा रहा हूँ अलग से जब निम्न परीक्षण चल रहा है?
यह मेरे लिए काम करता है। 'चेंज टाइप' अभी भी एक ऑब्जेक्ट देता है, लेकिन निहित कलाकार अब काम करता है। इसके अतिरिक्त, अब मैं 'tryCatchException' की बजाय' FormatException' की जांच करता हूं 'try/catch' ब्लॉक में। संक्षिप्त और सरल जवाब। – Scott
आगे की जांच के बाद, आप इसे शून्य प्रकारों के साथ उपयोग नहीं कर सकते हैं। तो इस आलेख का उपयोग करना: http://aspalliance.com/852 मैंने दोनों प्रकारों को संभालने के लिए एक विस्तार विधि लिखा है। – Scott