模块中的GetManifestResourceStream

时间:2014-12-31 00:15:56

标签: vb.net

我想将以下函数从表单移动到模块中,因为我计划在不同的“位置”使用此函数:

Public Function StreamFromResource(ByVal uFilename As String) As Stream

    Dim nAssembly As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()

    Dim s As Stream = nAssembly.GetManifestResourceStream(Me.GetType, uFilename)
    Debug.Assert(Not s Is Nothing)

    Return s

End Function

但是,VB.NET告诉我“Me”在模块中无效。 有人可以告诉我一个解决方法吗?

谢谢!

2 个答案:

答案 0 :(得分:1)

知道了:

Public Function StreamFromResource(ByVal uFilename As String) As Stream

    Dim nAssembly As System.Reflection.Assembly = System.Reflection.Assembly.GetExecutingAssembly()

    Dim s As Stream = nAssembly.GetManifestResourceStream(System.Reflection.MethodBase.GetCurrentMethod.DeclaringType, uFilename)
    Debug.Assert(Not s Is Nothing)

    Return s

End Function

答案 1 :(得分:0)

发布的解决方案没有任何问题,但是钟摆已摆向另一个极端:现在它只能用于模块。以下是一些灵活的方法:

' no need for Public
Friend Function GetResourceStream(obj As Object, filName As String) As Stream

    Dim t As Type = obj.GetType
    Dim asm As Assembly = t.Assembly
    Dim s As Stream = asm.GetManifestResourceStream(t, filName)

    Return s
End Function

' usage:
Dim ss As Stream = GetResourceStream(Me, strFile)

更可重复使用的是Extensions:

<Extension>
Friend Function GetResourceStream(obj As Object, filName As String) As Stream

    Dim T As Type = obj.GetType
    Dim asm As Assembly = T.Assembly
    Dim s As Stream = asm.GetManifestResourceStream(T, filName)

    Return s
End Function

<Extension>
Friend Function GetResourceStream(T As Type, filName As String) As Stream

    Dim asm As Assembly = T.Assembly
    Dim s As Stream = asm.GetManifestResourceStream(T, filName)
    Return s

End Function

第一个是最简单的,但只能从这个程序集中加载:

Dim s = Me.GetResourceStream(strFile)

第二个有点麻烦,但更灵活:

Dim s = GetType(Foo).GetResourceStream(strFile)

虽然笨拙,但它允许Type(Foo)充当资源&#34;定位器&#34;。如果资源位于不同的程序集中,请在同一程序集中定义Foo以从中加载资源。理想情况下,您使用的是应用已经使用的真实类型,但如果没有,则空FooResLocator类将起作用。

您也可以将扩展名重新定义为Friend Shared,以便在实用程序类中使用。