Cast object to T

前端 未结 8 1171
别那么骄傲
别那么骄傲 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 10:58

    First check to see if it can be cast.

    if (readData is T) {
        return (T)readData;
    } 
    try {
       return (T)Convert.ChangeType(readData, typeof(T));
    } 
    catch (InvalidCastException) {
       return default(T);
    }
    

提交回复
热议问题