문제

I am trying to instantiate a List with just a string for each list item. I am using the Google APIs library for their Prediction API, and when I go to set the input body (InputValue.CsvInstance), it is expecting a type of IList.

InputValue.CsvInstance is a virtual IList and is described as a list of input features which can be strings or doubles.

var body = new Google.Apis.Prediction.v1_6.Data.Input();

IList<string> list = new List<string>();
list.Add("this is some text in english!");

body.InputValue.CsvInstance = (IList<object>)list;  //fails here

I have tried creating just IList, but I get an invalid cast exception when trying to cast it to IList.

I have tried creating a IList, and populating it with strings, but at runtime it throws a Null exception error.

Can someone please provide me an example of how I would create this IList so I can set the CsvInstance?

EDIT: So I'm not sure this has to do with how I am creating the List<>. I'm thinking I'm not using the client library properly.

I'm trying to call this function: PredictRequest

It seems like the body of the request needs to be of type Google.Apis.Prediction.v1_6.Data.Input() and that's where I am running into issues setting the InputValue.CsvInstance: InputValue

도움이 되었습니까?

해결책

An IList<object> is not the same as an IList<string>, basically they are completely different classes.

Try this:

IList<object> list = new List<object>();
list.Add("this is some text in english!");

body.InputValue.CsvInstance = list;

다른 팁

I'm not well versed in this, but I have looked at it before. I'd read up on covariance and contravariance and see if it helps. If I'm reading it correctly, then you should be able to allow it to implicitly convert since your casting to a less derived type (i.e. covariance).

Update: I did a little testing. Converting IList is not covariant and so it will not allow you to convert, but IEnumerable is. If you need to store the list as strings and not objects, then you have the option of creating a new list of objects from that in a pretty concise, though likely with a pretty good performance hit. See my code below:

        List<string> strings = new List<string>();
        strings.Add("test1");

        IList<object> objectList = strings; // Error at compile time
        IEnumerable<object> objectEnumerable = strings; // Works fine, but is not an IList<object>

        IList<object> stringObjects = new List<object>(strings); // Works, but creates a whole new list to do it.

I found this worked:

IList<object> vals = "0,-0.25,430,-1.63,250,-1.75".Split(',');
Input input = new Input();
input.InputValue = new Input.InputData();
input.InputValue.CsvInstance = vals;
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top