如何覆盖整数,字符串等基本类型?

dyn*_*eed 5 vb.net types overriding

我正在为大型应用程序扩展vb.net中的一些基本数据类型.这包括integer,string,short等目前的情况是,我的新数据类型的对象有像MYInteger和myString的名字.由于这些是我用于我的应用程序的唯一类型,并且它们大多与默认类型兼容,有没有办法可以覆盖我的默认值,所以当你Dim iThing as Integer实际使用我稍微定制的整数类型时?

Mik*_*ron 8

不,如果可以的话,想象一下可能造成的混乱.在这种情况下有两种可能性:

  1. 在同一进程中运行的所有代码都将使用这些类型,甚至是不期望它的代码.坏.

  2. 你的概念Integer不同于CLR的概念Integer,突然两个相同类型的对象是不同的.坏.

可以向密封类型添加扩展方法.就像是:

Module MyExtensions
    <Extension()>
    Public Function Extended(i as Integer) As Integer
        return i + 4
    End Function
End Module

4.Extended() ' evaluates to 8
Run Code Online (Sandbox Code Playgroud)