zoukankan      html  css  js  c++  java
  • 未签名有元程序集 Unsigned Friend Assemblies

    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

  • 相关阅读:
    数据库被注入daxia123原因及解决办法
    Alipay数字证书管理员权限问题
    关闭数据库的xp_cmdshell命令以防止黑客攻击
    如何使用JavaScript来写ASP程序
    VBscript操作DOM
    如何做好性能压测丨压测环境设计和搭建
    10倍性能提升!DLA SQL推出基于Alluxio的数据湖分析加速功能
    高德地图驾车导航内存优化原理与实战
    「直播实录」中英数据库专家谈:数据库的过去、未来和现在
    Flink 助力美团数仓增量生产
  • 原文地址:https://www.cnblogs.com/xiao9426926/p/6015710.html
Copyright © 2011-2022 走看看