简体   繁体   中英

How to cast an object to internal class

I am viewing source code of an internal .Net class and want to modify a function using reflection. (By rewriting every single line of the original function into a new function using reflection and add my modification into it)

object responseObject = request.ConnectionAsyncResult.InternalWaitForCompletion();
ConnectStream writeStream = responseObject as ConnectStream;
if (writeStream == null) ...

How should I write the second line of the code ?

The code is checking if an object is specific class but I have no idea how to do this if the class is an internal class. How to cast an object into an internal class?

ConnectStream is an internal class

Well, you don't. You'll just have to use reflection for every single step - the compiler sure isn't going to help you :)

"Rewriting every single line" is a bad idea anyway - it's a bit trickier to get code that actually works. Instead, you'll probably just want to make your helper method call the original method, as well as do whatever you need done.

When using reflection, you don't need to know the types at compile-time, and you don't need to abide to all C#'s rules. A code that's roughly equivalent to your original could look something like this:

if (responseObject != null && responseObject.GetType().Name == "ConnectStream")

Depending on your actual needs, there are better ways to make that check as well - for example, you could take the System.Net assembly and find the ConnectStream type with the proper namespace and everything, and compare the two Type instances directly. But in code like this, it isn't really necessary.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM