Vb.net 如何在多个项目中使用扩展方法

Vb.net 如何在多个项目中使用扩展方法,vb.net,enums,extension-methods,Vb.net,Enums,Extension Methods,我有一个扩展方法,它应该检索枚举的Description属性值并返回与该属性关联的字符串。代码如下: <Extension()> Public Function GetEnumDescription(Of T)(ByVal e As T) As String If e.GetType().IsEnum Then Dim type As Type = e.GetType() Dim values As Array = [Enum].GetVal

我有一个扩展方法,它应该检索枚举的Description属性值并返回与该属性关联的字符串。代码如下:

<Extension()>
Public Function GetEnumDescription(Of T)(ByVal e As T) As String
    If e.GetType().IsEnum Then

        Dim type As Type = e.GetType()
        Dim values As Array = [Enum].GetValues(type)

        For Each Val As Integer In values
            If Val = Convert.ToInt32(e) Then
                Dim memInfo = type.GetMember(type.GetEnumName(Val))
                Dim descriptionAttribute As DescriptionAttribute = memInfo(0).GetCustomAttributes((New DescriptionAttribute).GetType(), False).FirstOrDefault()

                If descriptionAttribute IsNot Nothing Then
                    Return descriptionAttribute.Description
                End If
            End If
        Next

        Return String.Empty
    End If

    Throw New InvalidOperationException("Caller is not an Enum")
End Function
我希望看到一个消息框,上面写着“这是value1的描述”,但我得到的却是一个错误,上面写着

“GetEnumDescription”不是“MyEnum”的成员


因此,我的问题是,如何使用ProjectA中为其他项目中的枚举定义的扩展方法?

我解决了我的问题。当我声明模块ExtensionMethods时,我没有在其上添加访问修饰符,因此它默认为“Friend”。将“Public”访问修饰符添加到模块声明中会将其暴露给其他项目。愚蠢的我://

我觉得代码很好。ProjectA上的.Net版本是否高于ProjectB?代码文件可以“链接”。将它们存储在与任何项目无关的地方。然后,将它们添加到项目中时,使用
添加
按钮(在FileOpenDialog中)上的下拉列表添加为Link@N0Alias,这两个项目都以.NET Framework 4为目标。@Protoix,我尝试将带有扩展的模块移动到一个中立位置,并像您建议的那样在我的项目中添加指向它的链接。问题是,GetEnumDescription()函数不再工作。当它到达行
Dim descriptionAttribute As descriptionAttribute=memInfo(0).GetCustomAttributes((新的descriptionAttribute).GetType(),False).FirstOrDefault()
时,它抛出以下错误:找不到类型“descriptionAttribute()”上的公共成员“FirstOrDefault”。您可以创建主题扩展集(如DateTime、排序、成像等)如我所述,这是不同项目所需的链接。这正是您所问的(项目到项目),因此我没有发布完整答案。缺少成员只是意味着缺少导入。
Public Enum MyEnum
    <Description("This is value1's description")> value1
    <Description("This is value2's description")> value2
End Enum
Dim val As MyEnum = MyEnum.value1
MessageBox.Show(val.GetEnumDescription())