简体   繁体   中英

How to find the real type when Interface is returned?

If I have a function

public IEnumerable<string> GetStrings()
{
    return new string[]{"all","my","strings"};
} 

Is there any way I can determine the "real" type of the returned value (string[])? Reflection gives me:

Name: "IEnumerable`1"
Namespace: "System.Collections.Generic"
FullName: "System.Collections.Generic.IEnumerable`1[[System.String, mscorlib, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089]]"

The end goal is to instantiate an object of this type, serialize it and use as an example for api discovery.

It's so easy.

var result = GetStrings();    
var returnType = result.GetType();

It is not possible to get the real return type without calling the method. What if the method is something like this?

Random random = new Random();
public IEnumerable<string> GetStrings()
{
    var randomValue = random.Next();
    if (randomValue % 5 == 3)
        return new string[] { "all", "my", "strings" };
    else if (randomValue > 15)
        return new List<String>() { "all", "my", "strings" };
    else if (randomValue > 25)
        return new HashSet<String>() { "all", "my", "strings" };

    return null;
}

Reflection will not help you here, it can only tell you what the signature of the method says it returns (In your case an IEnumerable<string> ).

One way to find out, is to call the method and examine the returned object

var result = myInstance.GetString();
Console.WriteLine(result.GetType()); // System.String[]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM