i have a method with a return type of IEnumerable<T>
, and I need to capture the output of this method in a variable. I cannot use var to declare the variable, because the variable has to be declared outside of my try/catch block. So, what concrete Type can I use to declare my variable, that will accept the IEnumerable<T>
output of my method? Here's what this scenario looks like:
IEnumerable<string> CalleeMethod() {...}
IEnumerable<string> CallerMethod()
{
List<string> temp = null;
try
{
temp = CalleeMethod();
}
catch(Exception exception)
{
Debug.WriteLine(exception.GetBaseException().Message);
}
return temp;
}
This example doesn't work because when I declare temp
as List<T>
, I get the error: cannot convert IEnumerable<T> to List<T>
. I know I can call .ToList()
, or cast the output of CalleeMethod()
to List<T>
, but I am wanting to simply define the temp
variable with a concrete Type that can hold the IEnumerable<T>
output of CalleeMethod()
without having to cast it. So, what concrete Type can I declare temp
as that will not throw the cannot convert...
error?
Thanks in advance for any help!
您是否尝试过IEnumerable<String>
?
只需使用IEnumerable<string> temp = Enumerable.Empty<String>();
@hvd is correct. I think you have some concepts crossed. 'IEnumerable T' is different then 'IEnumerable string '. This is a simple generic version...
public class GenericTest
{
public IEnumerable<T> CalleeMethod<T>() where T : class
{
return new List<T>();
}
}
[TestMethod]
public void IEnumberableT()
{
var x = new GenericTest();
IEnumerable<string> result = x.CalleeMethod<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.