Cast object to T

前端 未结 8 1158
别那么骄傲
别那么骄傲 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:44

    You can presumably pass-in, as a parameter, a delegate which will convert from string to T.

    0 讨论(0)
  • 2020-12-07 10:48

    Have you tried Convert.ChangeType?

    If the method always returns a string, which I find odd, but that's besides the point, then perhaps this changed code would do what you want:

    private static T ReadData<T>(XmlReader reader, string value)
    {
        reader.MoveToAttribute(value);
        object readData = reader.ReadContentAsObject();
        return (T)Convert.ChangeType(readData, typeof(T));
    }
    
    0 讨论(0)
  • 2020-12-07 10:53

    Add a 'class' constraint (or more detailed, like a base class or interface of your exepected T objects):

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

    or where T : IMyInterface or where T : new(), etc

    0 讨论(0)
  • 2020-12-07 10:57

    try

    if (readData is T)
        return (T)(object)readData;
    
    0 讨论(0)
  • 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);
    }
    
    0 讨论(0)
  • 2020-12-07 11:01

    Actually, the problem here is the use of ReadContentAsObject. Unfortunately, this method does not live up to its expectations; while it should detect the most appropirate type for the value, it actually returns a string, no matter what(this can be verified using Reflector).

    However, in your specific case, you already know the type you want to cast to, therefore i would say you are using the wrong method.

    Try using ReadContentAs instead, it's exactly what you need.

    private static T ReadData<T>(XmlReader reader, string value)
    {
        reader.MoveToAttribute(value);
        object readData = reader.ReadContentAs(typeof(T), null);
        return (T)readData;
    }
    
    0 讨论(0)
提交回复
热议问题