Internal class masked by object

别等时光非礼了梦想. 提交于 2020-01-17 02:27:07

问题


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:


  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.

  2. List<A> implements the non-generic IList, so you can cast back to IEnumerable or IList 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 firstElvariable 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!