【问题标题】:When code is contained inside < > for Visual Basic当代码包含在 < > for Visual Basic 中时
【发布时间】:2018-11-05 05:20:44
【问题描述】:

在使用vb.net时,如果代码包含在“”符号内,比如命名空间,它告诉编译器做什么?还有,这样用的时候叫什么牌子呢?

为了明确问题;我知道括号“()”通常用于参数,括号“[]”用于声明新类型,但我找不到小于/大于符号在类似容量中的作用。

我浏览了我的参考书,并试图通过互联网对此进行研究,但我还没有找到答案。很可能是因为我不知道这些究竟会被命名为什么。我总是谈论关系运算符的结果,这不是我要寻找的。​​p>

这是我正在查看的示例:

Imports System.ComponentModel.Design

'<CLSCompliant(True)>
<System.ComponentModel.DefaultEvent("DataReceived")> _
Public Class SerialDF1forSLCMicroCon
Inherits MfgControl.AdvancedHMI.Drivers.DF1ForSLCMicroPLC5
Implements System.ComponentModel.IComponent
Implements System.ComponentModel.ISupportInitialize

Private Shared ReadOnly EventDisposed As New Object()
Public Event Disposed As EventHandler Implements System.ComponentModel.IComponent.Disposed

Protected m_synchronizationContext As System.Threading.SynchronizationContext

具体来说,我正在查看包含的行

<System.ComponentModel.DefaultEvent("DataReceived")> _

【问题讨论】:

  • 显示此类代码的示例。
  • 使用语法的一种方式是使用泛型。请使用您看到的代码示例编辑问题,这样我们就可以确定。
  • 表示attribute
  • @SamM,人字形(尖括号)仅在 C# 中用于泛型。 VB 使用括号括住泛型类型参数。
  • 括号不用于声明新类型。括号用于强制将关键字解释为标识符。例如,如果您想将属性命名为 Class,则必须将属性名称括在括号中,否则您会因为错误地使用 Class 关键字而出现语法错误:Public Property [Class]() As SomeType

标签: vb.net


【解决方案1】:

这是一个attribute。这是一种将元数据(附加信息)附加到代码中的方法,以后可以使用反射进行查询。

例如,假设您有一系列类(例如,Customer、Contact、Order、Product 等),每个类对应一个数据库表,并继承自 DbTable 基类,该基类有一个共同的DeleteAll() 方法。

现在,您的数据库表名可能与您的类名不匹配。在这种情况下,您可以定义一个向您的类添加附加信息的属性,提供表名,如下所示:

<DbTableName("CUST01")>
Public Class Customer
   Inherits DbTable

   ...
End Class

这表明您的“客户”对象存储在数据库的“CUST01”表中。

你可以这样实现属性:

Public Class DbTableNameAttribute
   Inherits System.Attribute

   Public Property Name As String

   Public Sub New(value As String)
      Name = value
   End Sub
End Class

最后,在您的基础 DbTable 类中,您将像这样实现 DeleteAll()

Public MustInherit Class DbTable
   Public Sub DeleteAll()
      ' Use reflection to retrieve the attribute.
      Dim attributes = Me.GetType().GetCustomAttributes()
      Dim dbTableNameAttribute = attributes.FirstOrDefault(Function(x) x.GetType() = GetType(DbTableNameAttribute)

      If dbTableNameAttribute IsNot Nothing Then
         Dim tableName As String = CType(dbTableNameAttribute, DbTableNameAttribute).Name

         ' tableName will contain the value specified in the attribute (e.g. "CUST01")
         Dim sql As String = "delete from " & tableName

         ' ... at this point you would send the delete command to your database ...
      End If
   End Sub
End Class

现在,在您引用的具体示例中:&lt;System.ComponentModel.DefaultEvent("DataReceived")&gt;

可能发生的情况是SerialDF1forSLCMicroCon 类可能有多个事件,并且该属性向设计人员提供了“DataReceived”事件是默认事件的提示。您会在 Windows 窗体按钮中看到类似的东西。如果你点击一个Button的事件,有很多,但是“Click”事件默认总是高亮的,因为它是最常用的。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-01-31
    • 2013-03-07
    • 2015-04-23
    • 1970-01-01
    相关资源
    最近更新 更多