将IList <Object>转换为IList <CustomObject>?

Dan*_*npe 1 c# json casting object javascriptserializer

我创建了一个通用函数,它可以检索JSON并解析它:

    public IList<Object> RetrieveView(string result)
    {
        JavaScriptSerializer ser = new JavaScriptSerializer();

        IList<Object> values = ser.Deserialize< IList<Object> >(result);

        return values;
    }
Run Code Online (Sandbox Code Playgroud)

我有很多使用它的类的问题.例如,当我尝试使用此:

IList<Receipt> receipts = (IList<Receipt>)RetrieveView(result);
Run Code Online (Sandbox Code Playgroud)

我明白了 InvalidCastException Unable to cast object of type 'System.Collections.Generic.List[System.Object]' to type 'System.Collections.Generic.IList[Receipt]'.

无论如何要保持我的功能Generic并能够将它投射到我的所有类/模型?

Jak*_*cki 6

使您的功能通用:

    public IList<T> RetrieveView<T>(string result)
    {
        JavaScriptSerializer ser = new JavaScriptSerializer();

        IList<T> values = ser.Deserialize< IList<T> >(result);

        return values;
    }
Run Code Online (Sandbox Code Playgroud)