首页 > 技术文章 > 未签名有元程序集 Unsigned Friend Assemblies

xiao9426926 2016-10-31 14:18 原文

C#中的访问修饰符internal可以使类型在同程序集中可以被相互访问。但有时会有这样一个要求,我们希望一个程序集中的类型可以被外部的某些程序集访问,如果设置成public的话,就被所有的外部程序集访问;或是在单元测试中,测试代码在另一个程序集中运行,但需要访问正在测试的标记为internal的程序集中的成员。要达到上述要求我们可以使用有元程序集。

看例子:

我是在D盘上新建了一个“friend Assembly”文件夹,把所有的文件(.dll、.cs、.exe)都放在里面。

1. 新建一个类库,friend_unsigned_A.cs

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Runtime.CompilerServices;

//friend_unsigned_A.cs
//Compile with
//csc/target:library friend_unsigned_A.cs

[assembly: InternalsVisibleTo ("friend_unsigned_B")] //定义friend_unsigned_B为有元程序集

namespace friend_unsigned_A
{
    //Type is internal by default
    class Class1
    {
        public void Test()
        {
            Console.WriteLine("Class1.Test");
        }
    }

    //Public type with internal member
    public class Class2
    {
        internal void Test()
        {
            Console.WriteLine("Class2.Test");
        }
    }
}

2. 打开VS开发人员命令行,csc /target:library friend_unsigned_A.cs

3. 新建一个控制台应用程序

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using friend_unsigned_A; //不要忘记添加命名空间

// friend_unsigned_B.cs
// Compile with: 
// csc /r:friend_unsigned_A.dll /out:friend_unsigned_B.exe friend_unsigned_B.cs
namespace friend_unsigned_B
{
    class Program
    {
        static void Main(string[] args)
        {
            // Access an internal type.
            Class1 inst1 = new Class1();
            inst1.Test();

            Class2 inst2 = new Class2();
            // Access an internal member of a public type.
            inst2.Test();

            System.Console.ReadLine();
        }
    }
}

4. 输入命令行 

csc /r:friend_unsigned_A.dll /out:friend_unsigned_B.exe friend_unsigned_B.cs

 

5. 直接运行 friend_unsigned_B.exe

推荐阅读