2010-10-07 19 views
6

मैं दृढ़ता से टाइप किए गए फैशन में 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'.

मैं (या कम से सांख्यिक लोगों पर) प्रत्येक कास्टिंग मामले को संभालने के लिए करने जा रहा हूँ अलग से जब निम्न परीक्षण चल रहा है?

उत्तर

11

आप भी आजमा सकते Convert.ChangeType

Convert.ChangeType(element.Value, typeof(TElementType)) 
+0

यह मेरे लिए काम करता है। 'चेंज टाइप' अभी भी एक ऑब्जेक्ट देता है, लेकिन निहित कलाकार अब काम करता है। इसके अतिरिक्त, अब मैं 'tryCatchException' की बजाय' FormatException' की जांच करता हूं 'try/catch' ब्लॉक में। संक्षिप्त और सरल जवाब। – Scott

+0

आगे की जांच के बाद, आप इसे शून्य प्रकारों के साथ उपयोग नहीं कर सकते हैं। तो इस आलेख का उपयोग करना: http://aspalliance.com/852 मैंने दोनों प्रकारों को संभालने के लिए एक विस्तार विधि लिखा है। – Scott

1

सी # में आप स्ट्रिंग ऑब्जेक्ट को Int32 पर नहीं डाल सकते हैं। उदाहरण के लिए इस कोड संकलन त्रुटि पैदा करता है: Convert class या Int32.Parse और Int32.TryParse विधियों का उपयोग करने

string a = "123.4"; 
    int x = (int) a; 

कोशिश करता है, तो आप इस तरह के कार्यक्षमता चाहते हैं।
और हाँ, यदि आप स्ट्रिंग को int में डालना चाहते हैं, तो आपको संख्यात्मक कास्टिंग अलग से संभालना चाहिए।

2

आप आप उपयोग Int32 की इस बात के लिए Parse या TryParse तरीकों की जरूरत है Int32 करने के लिए String से एक अस्पष्ट या स्पष्ट डाली ऐसा नहीं कर सकते। आप शायद कुछ निफ्टी एक्सटेंशन विधियां बना सकते हैं, उदाहरण:

using System; 
    using System.Diagnostics; 
    using System.Globalization; 
    using System.Text; 

    /// <summary> 
    /// Provides extension methods for strings. 
    /// </summary> 
    public static class StringExtensions 
    { 
     #region Methods 
     /// <summary> 
     /// Converts the specified string to a <see cref="Boolean"/> 
     /// </summary> 
     /// <param name="string">The string to convert.</param> 
     /// <returns>The specified string as a <see cref="Boolean"/>.</returns> 
     public static bool AsBoolean(this string @string) 
     { 
      return bool.Parse(@string); 
     } 

     /// <summary> 
     /// Converts the specified string to a <see cref="Boolean"/> using TryParse. 
     /// </summary> 
     /// <remarks> 
     /// If the specified string cannot be parsed, the default value (if valid) or false is returned. 
     /// </remarks> 
     /// <param name="string">The string to convert.</param> 
     /// <param name="default">The default value for if the value cannot be parsed.</param> 
     /// <returns>The specified string as a <see cref="DateTime"/>.</returns> 
     public static bool AsBooleanNonStrict(this string @string, bool? @default = null) 
     { 
      bool @bool; 
      if ((!string.IsNullOrEmpty(@string)) && bool.TryParse(@string, out @bool)) 
       return @bool; 

      if (@default.HasValue) 
       return @default.Value; 

      return false; 
     } 

     /// <summary> 
     /// Converts the specified string to a <see cref="DateTime"/> 
     /// </summary> 
     /// <param name="string">The string to convert.</param> 
     /// <returns>The specified string as a <see cref="DateTime"/>.</returns> 
     public static DateTime AsDateTime(this string @string) 
     { 
      return DateTime.Parse(@string); 
     } 

     /// <summary> 
     /// Converts the specified string to a <see cref="DateTime"/> using TryParse. 
     /// </summary> 
     /// <remarks> 
     /// If the specified string cannot be parsed, <see cref="DateTime.MinValue"/> is returned. 
     /// </remarks> 
     /// <param name="string">The string to convert.</param> 
     /// <param name="default">The default value for if the value cannot be parsed.</param> 
     /// <returns>The specified string as a <see cref="DateTime"/>.</returns> 
     public static DateTime AsDateTimeNonStrict(this string @string, DateTime? @default = null) 
     { 
      DateTime datetime; 
      if ((!string.IsNullOrEmpty(@string)) && DateTime.TryParse(@string, out datetime)) 
       return datetime; 

      if (@default.HasValue) 
       return @default.Value; 

      return DateTime.MinValue; 
     } 

     /// <summary> 
     /// Converts the specified string to a <see cref="TEnum"/> 
     /// </summary> 
     /// <param name="string">The string to convert.</param> 
     /// <returns>The specified string as a <see cref="TEnum"/>.</returns> 
     public static TEnum AsEnum<TEnum>(this string @string) where TEnum : struct 
     { 
      return (TEnum)Enum.Parse(typeof(TEnum), @string); 
     } 

     /// <summary> 
     /// Converts the specified string to a <see cref="TEnum"/> 
     /// </summary> 
     /// <param name="string">The string to convert.</param> 
     /// <returns>The specified string as a <see cref="TEnum"/>.</returns> 
     public static TEnum AsEnumNonStrict<TEnum>(this string @string, TEnum @default) where TEnum : struct 
     { 
      TEnum @enum; 
      if ((!string.IsNullOrEmpty(@string)) && Enum.TryParse(@string, out @enum)) 
       return @enum; 

      return @default; 
     } 

     /// <summary> 
     /// Converts the specified string to a <see cref="Int32"/> 
     /// </summary> 
     /// <param name="string">The string to convert.</param> 
     /// <returns>The specified string as a <see cref="Int32"/>.</returns> 
     public static int AsInteger(this string @string) 
     { 
      return int.Parse(@string); 
     } 

     /// <summary> 
     /// Converts the specified string to a <see cref="Int32"/> using TryParse. 
     /// </summary> 
     /// <remarks> 
     /// If the specified string cannot be parsed, the default value (if valid) or 0 is returned. 
     /// </remarks> 
     /// <param name="string">The string to convert.</param> 
     /// <param name="default">The default value for if the value cannot be parsed.</param> 
     /// <returns>The specified string as a <see cref="Int32"/>.</returns> 
     public static int AsIntegerNonStrict(this string @string, int? @default = null) 
     { 
      int @int; 
      if ((!string.IsNullOrEmpty(@string)) && int.TryParse(@string, out @int)) 
       return @int; 

      if (@default.HasValue) 
       return @default.Value; 

      return 0; 
     } 

     /// <summary> 
     /// Converts the specified string to a <see cref="bool"/> 
     /// </summary> 
     /// <param name="string">The string to convert.</param> 
     /// <returns>The specified string as a <see cref="DateTime"/>.</returns> 
     public static bool? AsNullableBolean(this string @string) 
     { 
      bool @bool; 
      if ((string.IsNullOrEmpty(@string)) || !bool.TryParse(@string, out @bool)) 
       return null; 

      return @bool; 
     } 

     /// <summary> 
     /// Converts the specified string to a <see cref="DateTime"/> 
     /// </summary> 
     /// <param name="string">The string to convert.</param> 
     /// <returns>The specified string as a <see cref="DateTime"/>.</returns> 
     public static DateTime? AsNullableDateTime(this string @string) 
     { 
      DateTime dateTime; 
      if ((string.IsNullOrEmpty(@string)) || !DateTime.TryParse(@string, out dateTime)) 
       return null; 

      return dateTime; 
     } 

     /// <summary> 
     /// Converts the specified string to a <see cref="DateTime"/> 
     /// </summary> 
     /// <param name="string">The string to convert.</param> 
     /// <returns>The specified string as a <see cref="DateTime"/>.</returns> 
     public static TEnum? AsNullableEnum<TEnum>(this string @string) where TEnum : struct 
     { 
      TEnum @enum; 
      if ((string.IsNullOrEmpty(@string)) || !Enum.TryParse(@string, out @enum)) 
       return null; 

      return @enum; 
     } 

     /// <summary> 
     /// Converts the specified string to a <see cref="Int32"/> 
     /// </summary> 
     /// <param name="string">The string to convert.</param> 
     /// <returns>The specified string as a <see cref="Int32"/>.</returns> 
     public static int? AsNullableInteger(this string @string) 
     { 
      int @int; 
      if ((string.IsNullOrEmpty(@string)) || !int.TryParse(@string, out @int)) 
       return null; 

      return @int; 
     } 
     #endregion 
    } 

मैं आमतौर पर इनका अक्सर उपयोग करता हूं।

0

स्ट्रिंग भी लागू करता IConvertible है, तो आप निम्नलिखित कर सकते हैं।

((IConvertible)mystring).ToInt32(null); 

आप इसे क्लीनर बनाने के लिए इसके आसपास कुछ एक्सटेंशन विधियां भी फेंक सकते हैं।

3

अपने कोड से, के बजाय:

return (TElementType)((object) element.Value); 

आप ऐसा करते हैं चाहते हैं:

return (TElementType) Convert.ChangeType(element.Value, typeof (T)); 

केवल यहाँ चेतावनी है कि TElementType IConvertible को लागू करना चाहिए है। हालांकि, अगर आप केवल आंतरिक प्रकारों के बारे में बात कर रहे हैं, तो वे सभी पहले ही लागू कर चुके हैं।

अपने कस्टम प्रकारों के लिए, मान लीजिए कि आप उन्हें यहां चाहते थे, तो आपको अपना स्वयं का रूपांतरण करना होगा।

संबंधित मुद्दे