Assume that class (B)'s public function has the return line:
return (object)(new List<A>{Some elements})
where A is an internal and sealed class. I cannot change the code of A or B.
After I call this function in B, how do I find the first element of that list. C# does not let me cast that list back into List<A>
because A is internal.
Just because you can read the source code or disassemble the code, you should not rely on the current implementation, rather try to use the public interface.
List<A>
implements the non-generic IList
, so you can cast back to IEnumerable
or IList
if you really look for trouble.
You can cast a generic List to the non-generic IEnumerable, iterate over that, and then use Object.ToString() to get information about the B instances, or you can just return the reference.
Object obj = new List<string> () { "dd", "ee" };
IEnumerable enumerable = obj as IEnumerable;
bool foundSomething = false;
foreach (var thing in enumerable)
{
if(!foundSomething)
{
// Console.Write(thing.ToString()); If you want
foundSomething = true;
return thing;
}
}
Perhaps I'm misunderstanding the question here, but if A is sealed, you can still write an extension method to iterate or handle the list.
You can use interface covariance to cast to IEnumerable<object>
and then use some of LINQ's extension methods:
var aItems = (IEnumerable<object>) B.Foo();
Console.WriteLine(aItems.First());
To get first element without touching anything you can do this:
object result = b.MethodThatReturnsList();
object firstEl = ((IList)result)[0];
Problem is that firstEl
variable can only be object
and you can't cast it to A because it is not accessible. Not very helpful though.
Here is the real problem: you can't declare public methods that return some private/internal types. You will get this compilation error .
Solution is to design a public interface that A will implement and return List<IYourInterface>
. Another option is to have public base class.
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.