2014-01-26 38 views
0

我只是想知道是否有可能取消調暗變量。有沒有UnDim變量的方法?

想象一下,這是我的#include文件,我使用的ASP頁面

Dim MyVar 
MyVar = "Hello World" 
Response.write(MyVar) 
'From now on I can not use Dim MyVar anymore as it throws an error 
'I have tried 
MyVar = Nothing 
Set MyVar = Nothing 
'But again, when you do 
Dim MyVar 
'It throws an error. 

這樣做的原因是,我不能使用相同的#INCLUDE文件超過每頁一次。是的,我喜歡使用Option Explicit,因爲它可以幫助我保持代碼清潔。

*)編輯:我看到它不是我想要的那麼清楚。

想象這是一個 「include.asp」

<% 
Dim A 
A=1 
Response.Cookie("beer")=A 
%> 

現在ASP頁:

<!--#include file="include.asp"--> 
<% 
'Now: I do not see whats in include above and I want to use variable A 
Dim A 
'And I get an error 
'I also cannot use the same include again: 
%> 
<!--#include file="include.asp"--> 

你明白我的意思?如果我能夠在包含結尾處UNDIM A變量,問題就會解決。

+1

我建議你不要試圖做到這一點,因爲它會在同一範圍內給出不同的含義MyVar的。爲什麼不將MyVar設置爲Nothing後重用?例如'MyVar =「Hello World2」'? – acarlon

回答

6

不,沒有辦法「UnDim」變量。幸運的是,你也不需要那個。

每當您嘗試在同一範圍內聲明兩次變量時,您已經犯了一個錯誤。考慮到運行時不允許你的幫助。

解決辦法:

  • 不要使用全局變量工作。使用函數,在那裏聲明你的變量。
  • 不要多次包含同一個文件。
+0

3.在模塊中聲明變量「Private」或「Public」,其意圖比使用Dim更清晰。 4.如果要保持狀態在函數之外,請使用類創建對象。 – AutomatedChaos

+0

@AutomatedChaos'Private'和'Public'只能在VBScript的類中使用。沒有模塊,就是VBA。 – Tomalak

+1

如果您使用'Windows腳本文件'(.WSF)或'HTML應用程序'(.HTA),則包含腳本,如'

1

我同意託默勒格 - 我真的不知道你爲什麼會需要(或希望)使用相同的文件兩次

這似乎是一個不好的設計理念,更好的(?)也許將include文件中的例程封裝爲可以調用的函數或子例程 - 不需要包含兩次。

此外,雖然你不能不開始,但你可以重燃,但我不想鼓勵不好的做法,因爲你似乎想要做什麼。

你可以使用這樣的事情,而不是一切:

Include.asp:

<% 
Function SetCookie(scVar, scVal) 
    Response.cookie (scVar) = scVal 
End Function 
%> 

ASP頁:

<!--#include file="include.asp"--> 
<% 
Dim A 
A=1 
SetCookie "Beer", A 

A=1 ' This is kind of redundant in this code. 

SetCookie "Beer", A 
%> 

但是如果你確實想使用全局變量,並堅持包含兩次,您可以通過爲全局變量添加另一個包含來這樣做。

Globals.asp:

<% 
Dim globalVarA 
...other global stuff here.... 
%> 

包含。ASP:

<% 
globalVarA=1 
Response.Cookie("beer")=globalVarA 
%> 

現在ASP頁:

<!--#include file="globals.asp"--> 
<!--#include file="include.asp"--> 
<% 
Dim A 
A=....something...... 
%> 
<!--#include file="include.asp"--> 
+0

OP有一定的機會嘗試使用IIS包含文件,如IIS服務器端包含('SSI')。這仍然是錯誤的,但它可以解釋爲什麼他不止一次地包括東西。 – Tomalak

相關問題