HttpServerUtility包含一个名为UrlEncode的公共函数.它不是共享功能.HttpServerUtility没有任何公共构造函数.
这样做失败了:
Dim encodeMe As String = "a string to be encoded!"
HttpServerUtility.UrlEncode(encodeMe) 'Bombs out
Run Code Online (Sandbox Code Playgroud)
这是有效的,也是微软的说法:
Dim instance As HttpServerUtility
Dim encodeMe As String = "a string to be encoded!"
instance.UrlEncode(encodeMe ) 'Works!
Run Code Online (Sandbox Code Playgroud)
他们是如何做到这一点的?您无法使用构造函数实例化它的实例,但只能通过引用HttpServerUtility.UrlEncode来访问UrlEncode.
编辑:虽然我非常喜欢每个人进入一个大的OO辩论,我相信问题是错误的MSDN文档."Dim instance As HttpServerUtility"这一行应该是"Dim instance As HttpServerUtility = Context.Server"我包含的代码(来自MSDN文档)实际上不起作用,而是抛出一个空引用异常 - 就像你一样期待.谢谢你,杰森!
jas*_*son 17
你确定这个有效吗?
Dim instance As HttpServerUtility
Dim encodeMe As String = "a string to be encoded!"
instance.UrlEncode(encodeMe) 'Works!
Run Code Online (Sandbox Code Playgroud)
这将NullReferenceException在运行时为您提供(编译器将为您提供instance未分配的警告).说真的,微软在这里没有做任何事情.上面的代码是灾难性的错误,并将在运行时死亡.
你做不到这一点
Dim encodeMe As String = "a string to be encoded!"
HttpServerUtility.UrlEncode(encodeMe) 'Bombs out
Run Code Online (Sandbox Code Playgroud)
因为UrlEncode没有被定义为一种Shared方法HttpServerUtility.
你需要一个非null的实例HttpServerUtility.正确的使用方式HttpServerUtility是这样的:
Dim instance As HttpServerUtility = HttpContext.Server
Dim s As String = "Hello, World!"
Dim result As String = instance.UrlEncode(s)
Run Code Online (Sandbox Code Playgroud)
另一种选择是只使用HttpUtility有一种Shared方法HttpUtility.UrlEncode:
Dim s As String = "Hello, World!"
Dim result As String = HttpUtility.UrlEncode(s)
Run Code Online (Sandbox Code Playgroud)