声明预计vb.net [英] declaration expected vb.net
问题描述
如何声明变量?
Imports System.Data.OleDb
公开 类 Form1
公共 constring1 作为 字符串
constring1 = Provider = MSDAORA.1; Password = temp; User ID = temp; Data Source = orcl1; Persist Security Info = True
结束 类
此处constring1显示错误:预期声明
请帮忙。
但是你没有在任何方法中进行字符串分配。你想这样做:公共 constring1 As String = Provider = MSDAORA.1; Password = temp; User ID = temp ; Data Source = orcl1; Persist Security Info = True
您可以在类范围内声明变量,但实际上不能在那个级别做任何事情。所以你做Pete所说的,并在声明中做出任务。
但是 ......宣布这通常是一种不好的做法类范围内的公共变量。如果这是常量 - 它可以使用但永远不会改变 - 添加Const
关键字,如下所示:公共 Const constring1 作为 String = Provider = MSDAORA.1; Password = temp; User ID = temp;数据源= orcl1;持久安全信息=真常量保存在内存的单独部分中,它们不受垃圾收集之类的影响。这也可以保护价值不被故意或意外地篡改。
Const
还在声明中添加了隐式Shared
,这意味着您可以使用类名访问它 -Form1.constring1
- 而不是使用实例。
因为你在表格上声明这个,大概是不将被用作一个类,为什么要将它作为Public
?面向对象编程中的一个经验法则是公开仅那些需要公开的元素。如果字符串仅在内部使用,请将其声明为Private
,或者受保护的
如果您将使用表单作为其他表单的基类。
您可能希望从基础知识中读取数据 - http://msdn.microsoft.com/en-us/library/aa290387%28v=vs.71%29.aspx [ ^ ]。
How to declare a variable?
Imports System.Data.OleDb
Public Class Form1
Public constring1 As String
constring1 = "Provider=MSDAORA.1;Password=temp;User ID=temp;Data Source=orcl1;Persist Security Info=True"
End Class
Here constring1 is showing error: Declaration expected
Please help.
You don't have your string allocation inside any method though. You want to do this:Public constring1 As String = "Provider=MSDAORA.1;Password=temp;User ID=temp;Data Source=orcl1;Persist Security Info=True"
You can declare variables at the class scope, but you cannot actually do anything at that level. So you do what Pete said, and make the assignment in the declaration.
BUT... it is generally a bad practice to declare public variables at the class scope. If this is a constant -- it is available for use but will never be changed -- add theConst
keyword, like so:Public Const constring1 As String = "Provider=MSDAORA.1;Password=temp;User ID=temp;Data Source=orcl1;Persist Security Info=True"Constants are kept in a separate section of memory where they are not subjected to things like garbage collection. This will also protect the value from being tampered with, either deliberately or accidentally.
Const
also adds an implicitShared
to the declaration, meaning you would access it by using the class name --Form1.constring1
-- rather than by using an instance.
Since you are declaring this on a form, which presumably will be not be used as a class, why make itPublic
at all? A good rule of thumb in Object Oriented Programming is to expose only those elements that need to be exposed. If the string will be used only internally, declare it to bePrivate
, orProtected
if you will be using your form as a base class for other forms.
You might want to pickup reading from the basics - http://msdn.microsoft.com/en-us/library/aa290387%28v=vs.71%29.aspx[^].
这篇关于声明预计vb.net的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!