【问题标题】:Access to methods and properties in class library with limitation有限制地访问类库中的方法和属性
【发布时间】:2012-12-23 09:38:33
【问题描述】:

我有两个类库项目:DataAccessLibraryServiceLayerLibraryServiceLayerLibrary 需要访问DataAccessLibrary 的方法和属性,但其他项目不能访问DataAccessLibrary

我怎样才能做到这一点?

【问题讨论】:

    标签: c# visual-studio oop


    【解决方案1】:

    首先,您可能想知道是否真的需要通过编译时或运行时检查来确保正确访问 DataAccessLibrary。也许在编码指南和标准中规定其正确使用就足够了——然后相信开发人员会遵循这些指南。再说一次,我不知道你的情况:-)

    其次,您可能想知道是否真的有必要创建单独的项目。您可以将 DataAccessLibrary 实现为 ServiceLayerLibrary 中的内部类,然后它们就不会暴露给外部世界。

    如果你不想这样做,那么你可以让 DataAccessLibrary 的 public 方法 internal 然后像这样声明可见性:

    [assembly: InternalsVisibleTo("ServiceLayerLibrary")]
    

    这是否干净取决于您。就我个人而言,我不喜欢这种结构。

    【讨论】:

      【解决方案2】:

      让您的成员在 DataAcceessLibrary internal 中并使用 friend assemblies 以便 ServiceLibrary 可以访问它们。

      internal 关键字(在 C# 中)允许访问同一程序集中的其他类。 Friend 是 VB.Net 中的等效关键字。但是,如果您希望另一个程序集能够访问另一个程序集的“内部”内容(在 C# 中),那么您可以使用下面名为“Friend Assemblies”的 Web 链接中的方法,它将一个程序集的“内部”内容公开给另一个程序集.在此过程中,您实际上没有在 C# 中使用关键字friend 或friendly。这就是他们所说的这种关系,你说的是 [assembly:InternalsVisibleTo("MyAssembly")]。这在您有一个程序集利用您不想公开的另一个程序集的功能的情况下很有用。您还可以将此技术与强命名程序集一起使用,例如 [程序集:InternalsVisibleTo("MyAssembly, PublicKey=xXxXx")]。

      例子:

      using System.Runtime.CompilerServices;
      using System;
      
      [assembly: InternalsVisibleTo("ServiceLibrary")]
      
      // The class is internal by default. 
      class FriendClass
      {
          public void Test()
          {
              Console.WriteLine("Sample Class");
          }
      }
      
      // Public class that has an internal method. 
      public class ClassWithFriendMethod
      {
          internal void Test()
          {
              Console.WriteLine("Sample Method");
          }
      }    
      

      如果您需要 DataAccessLibrary 中的公共成员,您也可以使用 an alternative signing approach,这可能会更好。它可以通过使用 LinkCommand 和 StrongNameIdentityPermission 来实现(请参阅http://www.codeproject.com/Articles/339909/Limiting-the-accessibility-Another-way-of-Friend-A)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-02-15
        • 2011-07-27
        • 1970-01-01
        • 2011-08-11
        • 2018-11-07
        • 2021-11-16
        相关资源
        最近更新 更多