Cast object to T

前端 未结 8 1159
别那么骄傲
别那么骄傲 2020-12-07 10:42

I\'m parsing an XML file with the XmlReader class in .NET and I thought it would be smart to write a generic parse function to read different attributes generic

相关标签:
8条回答
  • 2020-12-07 11:02

    Actually, the responses bring up an interesting question, which is what you want your function to do in the case of error.

    Maybe it would make more sense to construct it in the form of a TryParse method that attempts to read into T, but returns false if it can't be done?

        private static bool ReadData<T>(XmlReader reader, string value, out T data)
        {
            bool result = false;
            try
            {
                reader.MoveToAttribute(value);
                object readData = reader.ReadContentAsObject();
                data = readData as T;
                if (data == null)
                {
                    // see if we can convert to the requested type
                    data = (T)Convert.ChangeType(readData, typeof(T));
                }
                result = (data != null);
            }
            catch (InvalidCastException) { }
            catch (Exception ex)
            {
                // add in any other exception handling here, invalid xml or whatnot
            }
            // make sure data is set to a default value
            data = (result) ? data : default(T);
            return result;
        }
    

    edit: now that I think about it, do I really need to do the convert.changetype test? doesn't the as line already try to do that? I'm not sure that doing that additional changetype call actually accomplishes anything. Actually, it might just increase the processing overhead by generating exception. If anyone knows of a difference that makes it worth doing, please post!

    0 讨论(0)
  • 2020-12-07 11:07

    You could require the type to be a reference type :

     private static T ReadData<T>(XmlReader reader, string value) where T : class
     {
         reader.MoveToAttribute(value);
         object readData = reader.ReadContentAsObject();
         return (T)readData;
     }
    

    And then do another that uses value types and TryParse...

     private static T ReadDataV<T>(XmlReader reader, string value) where T : struct
     {
         reader.MoveToAttribute(value);
         object readData = reader.ReadContentAsObject();
         int outInt;
         if(int.TryParse(readData, out outInt))
            return outInt
         //...
     }
    
    0 讨论(0)
提交回复
热议问题