简体   繁体   English

如何将对象强制转换为内部类

[英]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. 我正在查看内部.Net类的源代码,并希望使用反射修改函数。 (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 ConnectStream是一个内部类

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. 使用反射时,您不需要在编译时知道类型,也不需要遵守所有C#的规则。 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. 根据您的实际需要,还有更好的方法来进行检查 - 例如,您可以使用System.Net程序集并找到具有正确名称空间和所有内容的ConnectStream类型,并直接比较两个Type实例。 But in code like this, it isn't really necessary. 但在像这样的代码中,它并不是必需的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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