简体   繁体   English

如何在VB.NET中为静态类编写方法扩展?

[英]How to write a method extension for a static Class in VB.NET?

I would like to add a custom WriteColoredText method to the Console Class, to acces like this: 我想在Console类中添加一个自定义的WriteColoredText方法,如下所示:

Console.WriteColoredText(Parametters)

The problem is that I only found information about creating method extensions for specific datatypes but any about a method extension for a Class. 问题是我只找到了有关为特定数据类型创建方法扩展的信息,但是有关类的方法扩展的信息。

If this is not possibly, which similar alternatives I have? 如果这不可能,我有哪些类似的替代品?

The short answer is, you can't. 简短的回答是,你做不到。

Extension methods can only apply to object instances, but the Console class is static. 扩展方法只能应用于对象实例,但Console类是静态的。 The only solution is to write your own, completely separate class, say ConsoleEx , and implement any methods you want there. 唯一的解决方案是编写自己的,完全独立的类,比如说ConsoleEx ,并实现你想要的任何方法。

Extension methods make it possible to write a method that can be called as if it were an instance method of the existing type. 扩展方法可以编写一个可以被调用的方法,就好像它是现有类型的实例方法一样

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

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