如何“覆盖” C# 中的内部类?
我想在 System.Web.Script.Services.ScriptHandlerFactory 和内部类中的其他 .NET 内容中自定义一些内容。 不幸的是,这是一个内部类。 当尝试自定义此类中的方法时,我有哪些选项?
There's something I want to customize in the System.Web.Script.Services.ScriptHandlerFactory and other .NET stuff inside an internal class. Unfortunately, it's an internal class. What options do I have when trying to customize a method in this class?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(4)
您可能会发现这个最近的文章很有启发性。 基本上,它表示您不能覆盖任何标记为“内部”的内容,并且来源具有尽可能高的权威性。 您最希望的是一种扩展方法。
You might find this recent article enlightening. Basically, it says that you can't override anything marked
internal
, and the source is about as authoritative as it gets. Best you can hope for is an extension method.Internal 关键字表示代码单元(类、方法等)对于其所在的程序集是“公共的”,但对于任何其他程序集是私有的。
因为你们不在同一个议会中,所以你们什么也做不了。 如果它不是内部的,您可以在扩展类时在要重写的方法上使用 new 关键字(以隐藏原始实现)。
简而言之:你要成为 SOL。
我能想到你唯一能做的就是编写一个代理类,其中你的私有字段之一是你想要扩展的类,并且你实现它的所有方法并代理它们的调用。 这样你仍然可以自定义输出,但是你必须使用你的类,并且考虑到它被标记为内部,我不确定如果没有一些严重的黑客攻击,这是否可能。
这可以让你想要完成的事情成为可能,但它不会很美好。
The internal keyword signifies that a unit of code (class, method, etc.) is "public" to the assembly it is in, but private to any other assembly.
Because you are not in the same assembly, you cannot do anything. If it wasn't internal you could use the new keyword on the method you're overriding (to hide the original implementation) when extending the class.
In short: you are to be SOL.
The only thing i can think of you could do is write a proxy class, where one of your private fields is the class you'd want to extend and you implement all it's methods and proxy their calls. that way you can still customize output, but you'd have to get your class used, and considering it's marked internal, i'm not sure that's possible without some serious hacking.
This could make what you want to accomplish possible, but it won't be pretty.
我相信您可以使用 Reflection 来绕过类上的访问修饰符,因此也许您可以使用 Reflection.Emit 生成从内部类型继承的类型(但不是密封修饰符),不过我在网上找不到这样的例子。
这当然适用于访问类的私有成员,并且可能适用于非密封类的继承。 但如果目标方法尚未标记为虚拟,则没有多大帮助。
I believe you can use Reflection to get around the access modifiers on a class, so perhaps you can use Reflection.Emit to generate a type that inherits from an internal type (but NOT the sealed modifier), though I can't find an example of this online.
This certainly works for accessing private members of classes, and probably for inheritance of non-sealed classes. But it doesn't help much if the target methods are not already marked virtual.
这取决于装配。 这可能会违反某些许可(尽管它类似于某种静态链接),甚至可能使部署成为一场噩梦,但您可以考虑:
It depends on the assembly. This could possibly violate some licensing (although its similar to some sort of static linking), and maybe even make deployment a nightmare, but you could consider: