【问题标题】:How to use an extension method in multiple projects如何在多个项目中使用扩展方法
【发布时间】:2017-10-04 20:39:57
【问题描述】:

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

<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

当我在同一个项目中定义的各种类中使用它时,它就像一个魅力。但是,当我在另一个项目(相同的解决方案,我们称之为ProjectB)中工作时,我导入包含此扩展方法(ProjectA)的项目并尝试使用它,它不起作用。

假设我在 ProjectB 中声明了一个名为 MyEnum 的枚举。设置如下:

Public Enum MyEnum
    <Description("This is value1's description")> value1
    <Description("This is value2's description")> value2
End Enum

我正在使用 MyEnum 的 ProjectB 中的一个类,我想获取描述属性的值。我在 ProjectB 中添加对 ProjectA 的引用,然后添加 Import 语句以在我的类中使用 ProjectB。当我尝试做这样的事情时:

Dim val As MyEnum = MyEnum.value1
MessageBox.Show(val.GetEnumDescription())

我希望看到一个消息框,上面写着“这是 value1 的描述”,但我收到一个错误提示

“GetEnumDescription”不是“MyEnum”的成员

所以我的问题是如何在其他项目中使用我在 ProjectA 中为 Enums 定义的扩展方法?

【问题讨论】:

  • 该代码对我来说看起来不错。 ProjectA的.Net版本比ProjectB高吗?
  • 代码文件可以“链接”。将它们存储在与任何项目无关的地方。然后在将它们添加到项目时,使用Add 按钮(在 FileOpenDialog 中)上的下拉列表添加为链接
  • @N0Alias,这两个项目都针对 .NET Framework 4。
  • @Plutonix,我尝试将带有扩展名的模块移动到中性位置,并按照您的建议在我的项目中添加指向它的链接。问题是,GetEnumDescription() 函数不再起作用。当它到达Dim descriptionAttribute As DescriptionAttribute = memInfo(0).GetCustomAttributes((New DescriptionAttribute).GetType(), False).FirstOrDefault() 行时,它会抛出此错误:找不到类型“DescriptionAttribute()”上的公共成员“FirstOrDefault”。
  • 您可以创建主题扩展集(例如 DateTime、Sorting、Imaging 等),这些扩展集按照我所描述的这些不同项目的需要进行链接。这正是您所问的(项目到项目),所以我没有发布完整的答案。缺少的成员只是意味着缺少导入。

标签: vb.net enums extension-methods


【解决方案1】:

我发现了我的问题。当我声明模块 ExtensionMethods 时,我没有在其上放置访问修饰符,因此它默认为“Friend”。将“公共”访问修饰符添加到模块声明中会将其暴露给其他项目。傻我:/

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-03-09
    • 2020-11-02
    • 1970-01-01
    • 2011-02-09
    • 2021-11-29
    相关资源
    最近更新 更多