質問

I know that T is List<string> (or List<MyClass>). How should look reflection or something that allow me to return this List of string?

public T Deserialize<T>(string response)
{
    //just example
    string[] words = response.Split(' ');
    List<string> wordsList = words.ToList();
    //?
    return wordsList;
}

Background: Deserialize method is used to parse html data. It is something like own myJson.myDeserialize method used in Website, which does not have API.

役に立ちましたか?

解決

There is an awkward trick for achieving this: You need to first cast your instance to object.

public T Deserialize<T>(string response)
{
    string[] words = response.Split(' ');
    List<string> wordsList = words.ToList();

    return (T)(object)wordsList;
}

This assumes that your caller specifies List<string> as the generic type.

var x = Deserialize<List<string>>("hello world");    // gives "hello", "world"
var y = Deserialize<int>("hello world");             // throws InvalidCastException
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top