InternalsVisibleTo attribute isn't working

后端 未结 19 2516
眼角桃花
眼角桃花 2020-11-27 13:51

I am trying to use the InternalsVisibleTo assembly attribute to make my internal classes in a .NET class library visible to my unit test project. For some reas

19条回答
  •  囚心锁ツ
    2020-11-27 14:02

    Here's a macro I use to quickly generate this attribute. Its a bit hacky, but it works. On my machine. When the latest signed binary is in /bin/debug. Etc equivocation etc. Anyhow, you can see how it gets the key, so that'll give you a hint. Fix/improve as your time permits.

    Sub GetInternalsVisibleToForCurrentProject()
        Dim temp = "[assembly:  global::System.Runtime.CompilerServices." + _
                   "InternalsVisibleTo(""{0}, publickey={1}"")]"
        Dim projs As System.Array
        Dim proj As Project
        projs = DTE.ActiveSolutionProjects()
        If projs.Length < 1 Then
            Return
        End If
    
        proj = CType(projs.GetValue(0), EnvDTE.Project)
        Dim path, dir, filename As String
        path = proj.FullName
        dir = System.IO.Path.GetDirectoryName(path)
        filename = System.IO.Path.GetFileNameWithoutExtension(path)
        filename = System.IO.Path.ChangeExtension(filename, "dll")
        dir += "\bin\debug\"
        filename = System.IO.Path.Combine(dir, filename)
        If Not System.IO.File.Exists(filename) Then
            MsgBox("Cannot load file " + filename)
            Return
        End If
        Dim assy As System.Reflection.Assembly
        assy = System.Reflection.Assembly.Load(filename)
        Dim pk As Byte() = assy.GetName().GetPublicKey()
        Dim hex As String = BitConverter.ToString(pk).Replace("-", "")
        System.Windows.Forms.Clipboard.SetText(String.Format(temp, assy.GetName().Name, hex))
        MsgBox("InternalsVisibleTo attribute copied to the clipboard.")
    End Sub
    

提交回复
热议问题