问题
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.
回答1:
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-genericIList
, so you can cast back toIEnumerable
orIList
if you really look for trouble.
回答2:
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;
}
}
回答3:
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.
Extension methods for sealed class in c#
回答4:
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());
回答5:
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.
来源:https://stackoverflow.com/questions/38057618/internal-class-masked-by-object