如何在库保护的类中包括使用?

时间:2019-01-14 00:46:09

标签: c#

我为以下代码制作了一个库(dll文件),并且为下面的代码成功地为ClassLibrary1.dll创建了一个库文件:

 using System;
 using System.Collections.Generic;
 using System.Linq;
 using System.Text;
 using System.Data;
 using System.Windows.Forms;



 namespace ClassLibrary1
 {
    class A
    {
         protected int s11;

         protected int Lock11;
         protected int Queue11;
         protected int Singal11;

         protected A(int s, int Lock, int Queue, int Singal)
        {
            s11 = s;

            Lock11 = Lock;
            Queue11 = Queue;
            Singal11 = Singal;


        }

        // The constructor obtains the state information.


        protected int StartClient()
        {
            int status;

            status = s11 + Queue11 + Lock11 + Singal11;
             MessageBox.Show("hello!"+ status.ToString());



            return status;


        }
        public int TCall()
        {
            int status;
            status = StartClient();
            return status;
        }

    }


    class B : A
    {

        public B(int s, int Lock, int Queue, int Singal) : base(s, Lock, 
                Queue, Singal)
        {
            int status;
            // Can access protected int but not private int!
            status = TCall();

        }


    }


}

在我的App表单中,我需要使用B&TCall()类,问题是我无法使用它,在后续Form调用中应该怎么做:

     using System.Collections.Generic;
     using System.Data;
     using System.Drawing;
     using System.Text;
     using System.Windows.Forms;
     using ClassLibrary2;

     namespace MainForm
     {
        public partial class Form1 : Form
        {
            public Form1()
            {
                    InitializeComponent();
             }

            private void button1_Click(object sender, EventArgs e)
            {
                // how could I use class B in this area, since it was 
                 public in ClassLibrary2 ??
                         B cc = new B();    // likewise
            }
        }
     }

请帮助我如何使用受保护的库调用?

3 个答案:

答案 0 :(得分:0)

您可能想了解default access modifier of C#。在这种情况下,您在ClassLibrary1中的类是内部的。如果要在Winform项目中使用它们,请将它们公开或使用friend assembly

答案 1 :(得分:0)

是的,我在库(DLL)文件中包含了这两个命令行

 using System.Runtime.CompilerServices;

 [assembly: InternalsVisibleTo("MainForm")]

在我的Form App中,如以下代码所示:

 using ClassLibrary1;

 namespace MainForm
{ 
    public partial class Form1 : Form
    {
         public Form1()
        {
            InitializeComponent();
        }

    private void button1_Click(object sender, EventArgs e)
    {
        int s = 1;
        int a= 1;
        int b = 1;
        int c = 1;

        // how could I use class B in this area, since it was public in ClassLibrary2 ??
        B cc = new B(s, a, b, c);
    }
}

}

答案 2 :(得分:0)

您不能从表单中使用B,因为B不是公开的。但是,如果将其公开,则可以执行以下操作:

        private void button1_Click(object sender, EventArgs e)
        {
            var cc = new B(1,1,1,1);
        }