Instantiating an Internal class and casting it as a given type

十年热恋 提交于 2019-12-06 11:45:45

Given that you only know the type at execution time, there's really no such concept as "returning the object as the internal type". Think about what you'd want the method signature to look like... there's no way you could express it.

If the calling code knows about it in a strongly typed way, you should make the code generic instead:

public T InitPrivateCoreObjects<T>()
{
    Type type = typeof(T);
    ...
    return (T) newObject;
}

... but if the calling code doesn't know about it, that's not helpful to it.

If you could explain more about why you think you want this ability, we could try to suggest alteratives.

I can use Reflection.Emit to create a new class based on that type

Not really: code generated using Reflection.Emit follows the same rules as your own C#. You can't use it to bypass internal protection.

I've seen examples accessing individual methods and properties

That's what you'll need to do: use reflection to look up and invoke individual methods and properties.

A couple of alternatives:

  • Modify the internal class to implement some interface, and make that interface public. Call methods on the interface as normal.
  • Get [InternalsVisibleTo] working. This is the right way to go.

This is not really a direct answer to your question, but you may find this useful:

ExposedObject

If you don't have access to the internal type, nor does that type implement any public interface that you consider sufficient to interact with it, but you know beforehand the names and signatures of members on that type, this is probably your best choice.

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