扩展从基础对象继承的ENUM值

时间:2010-06-14 09:30:12

标签: vb.net

如果我在基础对象中定义了一个具有多个默认值的ENUM。当我从基础对象继承时,我想添加更多选项,ENUM列表是特定于继承对象的。

例如,我的基地可以有一个名为Direction的ENUM值:

ALL
停止
开始

我创建了一个新的类调用Compass,它继承了基类以及将以下内容添加到ENUM方向的内容。



西

我创建了一个新的类调用Navigation,它继承了基类以及将以下内容添加到ENUM方向的内容 左

所以,在我的继承类中,我是否扩展了ENUM。  我正在使用VB.NET。

2 个答案:

答案 0 :(得分:1)

你不能这样做,因为枚举是值类型,因此是密封的。

虽然他是一篇试图解决这个问题的代码项目文章:http://www.codeproject.com/KB/cs/EnumBuilder.aspx

答案 1 :(得分:0)

熟悉System.Reflection和System.Reflection.Emit命名空间,但如果使用ICollection(KeyValuePair(字符串,整数))或其他类似的东西,它可能会更好。

以下是EnumBuilder的vb.net示例,其中大部分是直接从http://msdn.microsoft.com/en-us/library/system.reflection.emit.enumbuilder.aspx复制的

Sub Main()
    Dim abcList As New List(Of String)
    For Each Item As String In [Enum].GetNames(GetType(FirstEnum))
        abcList.Add(Item)
    Next
    For Each Item As String In [Enum].GetNames(GetType(SecondEnum))
        abcList.Add(Item)
    Next
    For Each Item As String In [Enum].GetNames(GetType(ThirdEnum))
        abcList.Add(Item)
    Next

    Dim currentDomain As AppDomain = AppDomain.CurrentDomain

    ' Create a dynamic assembly in the current application domain, 
    ' and allow it to be executed and saved to disk.
    Dim aName As System.Reflection.AssemblyName = New System.Reflection.AssemblyName("TempAssembly")
    Dim ab As System.Reflection.Emit.AssemblyBuilder = currentDomain.DefineDynamicAssembly( _
        aName, System.Reflection.Emit.AssemblyBuilderAccess.RunAndSave)

    ' Define a dynamic module in "TempAssembly" assembly. For a single-
    ' module assembly, the module has the same name as the assembly.
    Dim mb As System.Reflection.Emit.ModuleBuilder = _
        ab.DefineDynamicModule(aName.Name, aName.Name & ".dll")

    Dim eb As System.Reflection.Emit.EnumBuilder = _
       mb.DefineEnum("MyNewEnum", System.Reflection.TypeAttributes.Public, GetType(Integer))

    ' Define members, set values (integer)
    Dim i As Integer = 0
    For Each item As String In abcList
        eb.DefineLiteral(item, i)
        i += 1
    Next

    Dim finished As Type = eb.CreateType() 'At this point, your System.RuntimeType exists with a BaseType of System.Enum
    ab.Save(aName.Name & ".dll")

    'finished.getEnumNames returns data similar to a NameValueCollection(of string,int32)

End Sub

Enum FirstEnum
    One
    Two
    Three
End Enum

Enum SecondEnum
    Four
    Five
    Six
End Enum

Enum ThirdEnum
    Seven
    Eight
    Nine
End Enum
相关问题