How to use a class from one C# project with another C# project

后端 未结 9 974
花落未央
花落未央 2020-11-27 15:12

In the same solution, I have two projects: P1 and P2. How can I make use of a class of P1 in P2?

9条回答
  •  攒了一身酷
    2020-11-27 15:46

    Paul Ruane is correct, I have just tried myself building the project. I just made a whole SLN to test if it worked.

    I made this in VC# VS2008

    << ( Just helping other people that read this aswell with () comments )

    Step1:

    Make solution called DoubleProject

    Step2:

    Make Project in solution named DoubleProjectTwo (to do this select the solution file, right click --> Add --> New Project)

    I now have two project in the same solution

    Step3:

    As Paul Ruane stated. go to references in the solution explorer (if closed it's in the view tab of the compiler). DoubleProjectTwo is the one needing functions/methods of DoubleProject so in DoubleProjectTwo right mouse reference there --> Add --> Projects --> DoubleProject.

    Step4:

    Include the directive for the namespace:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using DoubleProject; <------------------------------------------
    
    namespace DoubleProjectTwo
    {
        class ClassB
        {
            public string textB = "I am in Class B Project Two";
            ClassA classA = new ClassA();
    
    
            public void read()
            {
                textB = classA.read();
            }
        }
    }
    

    Step5:

    Make something show me proof of results:

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    
    namespace DoubleProject
    {
        public class ClassA    //<---------- PUBLIC class
        {
            private const string textA = "I am in Class A Project One";
    
            public string read()
            {
                return textA;
            }
        }
    }
    

    The main

    using System;
    using System.Collections.Generic;
    using System.Linq;
    using System.Text;
    using DoubleProjectTwo;  //<----- to use ClassB in the main
    
    namespace DoubleProject
    {
        class Program
        {
            static void Main(string[] args)
            {
                ClassB foo = new ClassB();
    
                Console.WriteLine(foo.textB);
                Console.ReadLine();
            }
        }
    }
    

    That SHOULD do the trick

    Hope this helps

    EDIT::: whoops forgot the method call to actually change the string , don't do the same :)

提交回复
热议问题