如何将 属性 恢复为默认值?

How can I revert a property to its default value?

Public Property Name() As String = "default_name"

Sub InitializeFields()
    Name = String.Empty
    '
    '
    '
    Name = Name.GetDefaultValue.ToString    '   an example

End Sub

如何以编程方式恢复任何 属性 的默认值“default_name”?

没有开箱即用的方法可以以某种方式将 属性 恢复为其(自定义)初始值。一改就完了;原始值丢失。

假设 属性 属于 class(并且它不会在构造函数中被修改),您 可以 通过以下方式检索值创建 class 的临时实例。例如:

Class SomeClass
    Public Property Name As String = "default_name"

    Sub InitializeFields()
        Name = String.Empty
        '
        '
        '
        Name = New SomeClass().Name
    End Sub
End Class

但是, 这不是很健壮,而且很快就会变得丑陋。我这样做的方法是将默认值存储在常量中:

Private Const DefaultName As String = "default_name"

Public Property Name As String = DefaultName

Sub InitializeFields()
    Name = String.Empty
    '
    '
    '
    Name = DefaultName
End Sub

然后您可以为以后访问其原始值所需的每个 属性 执行此操作。

下面是您应该如何使用实际默认值执行此操作的示例:

Imports System.ComponentModel

Public Class Thing

    <DefaultValue("Hello World")>
    Public Property WithDefault As String

    Public Property WithoutDefault As String

End Class
Imports System.ComponentModel
Imports System.Reflection

Module Module1

    Sub Main()
        Dim something As New Thing

        something.WithDefault = "First"
        something.WithoutDefault = "Second"

        If TrySetDefaultValue(something, NameOf(something.WithDefault)) Then
            Console.WriteLine($"{NameOf(something.WithDefault)} reset to ""{something.WithDefault}""")
        Else
            Console.WriteLine($"No default value for {NameOf(something.WithDefault)}")
        End If

        If TrySetDefaultValue(something, NameOf(something.WithoutDefault)) Then
            Console.WriteLine($"{NameOf(something.WithoutDefault)} reset to ""{something.WithoutDefault}""")
        Else
            Console.WriteLine($"No default value for {NameOf(something.WithoutDefault)}")
        End If
    End Sub

    Public Function TryGetDefaultValue([object] As Object, propertyName As String, ByRef value As Object) As Boolean
        Dim attribute = [object].GetType().GetProperty(propertyName).GetCustomAttribute(Of DefaultValueAttribute)()

        If attribute Is Nothing Then
            Return False
        End If

        value = attribute.Value

        Return True
    End Function

    Public Function TrySetDefaultValue([object] As Object, propertyName As String) As Boolean
        Dim [property] = [object].GetType().GetProperty(propertyName)
        Dim attribute = [property].GetCustomAttribute(Of DefaultValueAttribute)()

        If attribute Is Nothing Then
            Return False
        End If

        Dim value = attribute.Value

        [property].SetValue([object], value)

        Return True
    End Function

End Module

自己回答:

Imports System.Reflection
Imports System.ComponentModel

Public Class clsThisClass
    '   each property have attribute of default value
    <DefaultValue(0)>
    Public Property RecordCount() As Long = 0

    <DefaultValue("a")>
    Public Property SQL() As String = String.Empty

    <DefaultValue(0)>
    Public Property IndexID() As Long = 0

    <DefaultValue("b")>
    Public Property Name() As String = String.Empty

    <DefaultValue("c")>
    Public Property Title() As String = String.Empty

    <DefaultValue("d")>
    Public Property Document_No() As String = String.Empty

    <DefaultValue("abc")>
    Public Property Company_Code() As String = String.Empty

    Sub InitializeFields()
        With Me

            RecordCount = 28
            IndexID = 10
            Name = "name"
            Title = "title"
            Document_No = "doc_no"
            Company_Code = "com_code"

            Debug.WriteLine(RecordCount)
            Debug.WriteLine(IndexID)
            Debug.WriteLine(Name)
            Debug.WriteLine(Document_No)
            Debug.WriteLine(Company_Code)

'    revert or reset all properties to default value upon initialization
            Dim aType As Type = GetType(clsThisClass)
            '    each property of class
            For Each pi As System.Reflection.PropertyInfo In aType.GetProperties()
                '    grab assigned default value of the property
                Dim attribute = Me.GetType().GetProperty(pi.Name.ToString).GetCustomAttribute(Of DefaultValueAttribute)()
                Try
                    Dim value As Object = Nothing
                    '    convert value type according to the type of the property
                    value = CTypeDynamic(value, GetType(Attribute))

                    If Not attribute Is Nothing Then
                        value = attribute.Value
                        '    set default value
                        pi.SetValue(Me, value)

                    End If
                Catch ex As Exception

                End Try
            Next

            Debug.WriteLine(RecordCount)
            Debug.WriteLine(IndexID)
            Debug.WriteLine(Name)
            Debug.WriteLine(Document_No)
            Debug.WriteLine(Company_Code)

        End With
    End Sub
End Class

输出:

28

10

姓名

doc_no

com_code

0

0

一个

b

c

d

abc

一次用默认值初始化了所有属性。 在我的场景中,我有很多 classes 并且有几个属性。 通过执行这几行代码。我可以在每个 class 中复制粘贴初始化方法。节省了很多写代码的时间。