Cast object to T

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

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

    private static T ReadData(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

提交回复
热议问题