派生类中属性的替代属性

时间:2018-12-14 14:55:30

标签: .net vb.net

在类中继承时,如何在基类中覆盖带注释的属性?

基类示例:

<Serializable>
<XmlRoot("INTERFACE")>
Public MustInherit Class WM_Interface

    Private m_Message_Type As String
    Private m_Event_DTTM As String
    Private m_Business_Unit As String

    <XmlElement(ElementName:="MESSAGE_TYPE")>
    Public Property Message_Type() As String
        Get
            Return m_Message_Type
        End Get
        Set(value As String)
            m_Message_Type = value
        End Set
    End Property

    <XmlElement(ElementName:="EVENT_DTTM")>
    Public Property Event_DTTM() As String
        Get
            Return m_Event_DTTM
        End Get
        Set(value As String)
            m_Event_DTTM = value
        End Set
    End Property

    <XmlElement(ElementName:="BUSINESS_UNIT")>
    Public Property Business_Unit() As String
        Get
            Return m_Business_Unit
        End Get
        Set(value As String)
            m_Business_Unit = value
        End Set
    End Property
End Class

现在在派生类中,我想添加一个属性,但是我还想使BUSINESS_UNIT isNullable = False

<Serializable>
<XmlRoot("INTERFACE")>
Public Class DERIVED_WM_Interface
    Inherits WM_Interface

    Private m_NEWPROPERTY As String

    <XmlElement(ElementName:="NEWPROPERTY", IsNullable:=False)>
    Public Property NEWPROPERTY() As String
        Get
            Return m_NEWPROPERTY
        End Get
        Set(value As String)
            m_NEWPROPERTY = value
        End Set
    End Property

    'Also want to make isNullable = False for base class property of Business_Unit
    'How?
End Class

这可能吗?

1 个答案:

答案 0 :(得分:1)

我认为默认情况下它已经设置为False。但是,如果要更改它,只需覆盖该属性即可。

<Serializable>
<XmlRoot("INTERFACE")>
Class Class1

    <XmlElement(ElementName:="SomeProperty")>
    Public Overridable Property TestProperty As String

End Class

<Serializable>
<XmlRoot("INTERFACE")>
Class Class2
    Inherits Class1

    <XmlElement(ElementName:="SomeProperty", IsNullable:=True)>
    Public Overrides Property TestProperty As String

End Class

通过快速测试,您可以看到结果。

    For Each pi As PropertyInfo In GetType(Class1).GetProperties()
        Dim att As XmlElementAttribute

        att = CType(pi.GetCustomAttributes(GetType(XmlElementAttribute), True)(0), XmlElementAttribute)

        Console.WriteLine(att.IsNullable) ' Display: False
    Next

    For Each pi As PropertyInfo In GetType(Class2).GetProperties()
        Dim att As XmlElementAttribute

        att = CType(pi.GetCustomAttributes(GetType(XmlElementAttribute), True)(0), XmlElementAttribute)

        Console.WriteLine(att.IsNullable) ' Display: True
    Next