简体   繁体   English

如何将一个 C# 项目中的类与另一个 C# 项目一起使用

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

In the same solution, I have two projects: P1 and P2.在同一个解决方案中,我有两个项目:P1 和 P2。 How can I make use of a class of P1 in P2?如何在 P2 中使用 P1 类?

  1. In the 'Solution Explorer' tree, expand the P2 project and then right-click the project and select 'Add Reference' from the menu.在“解决方案资源管理器”树中,展开 P2 项目,然后右键单击该项目并从菜单中选择“添加引用”。
  2. On the 'Add Reference' dialog, select the 'Projects' tab and select your P1 project.在“添加引用”对话框中,选择“项目”选项卡并选择您的 P1 项目。
  3. If you are using namespaces then you will need to import the namespaces for your P1 types by adding 'using' statements to your files in P2.如果您使用命名空间,那么您将需要通过向 P2 中的文件添加“using”语句来导入 P1 类型的命名空间。

Note that the types in P1 that you wish to access directly must have a sufficient access level: typically this means they must be made public.请注意,您希望直接访问的 P1 中的类型必须具有足够的访问级别:通常这意味着它们必须公开。

只需从 P2 添加对 P1 的引用

Paul Ruane is correct, I have just tried myself building the project. Paul Ruane 是对的,我刚刚尝试自己构建该项目。 I just made a whole SLN to test if it worked.我刚刚制作了一个完整的 SLN 来测试它是否有效。

I made this in VC# VS2008我在 VC# VS2008 中做了这个

<< ( Just helping other people that read this aswell with () comments ) <<(只是通过 () 评论帮助其他阅读本文的人)

Step1:第1步:

Make solution called DoubleProject制作名为 DoubleProject 的解决方案

Step2:第2步:

Make Project in solution named DoubleProjectTwo (to do this select the solution file, right click --> Add --> New Project)在名为 DoubleProjectTwo 的解决方案中创建项目(为此选择解决方案文件,右键单击 --> 添加 --> 新建项目)

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. DoubleProjectTwo 是需要DoubleProject 的函数/方法的一个,所以在DoubleProjectTwo 中鼠标右键引用那里--> 添加--> 项目--> 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 :)编辑:::哎呀忘记了实际更改字符串的方法调用,不要这样做:)

All too often a new developer asks this simple question which is a common problem specifically with Visual Studio IDE's.新开发人员经常会问这个简单的问题,这是 Visual Studio IDE 的一个常见问题。 Few people answer the specific question and often critique the question or give "guesses" for solutions which don't answer the common problems.很少有人回答具体问题,并且经常批评问题或对没有回答常见问题的解决方案进行“猜测”。 The first common problem is the IDE leads you to create new projects rather than add new files (.java, .py, .cpp, .c) to the existing solution (by default it creates a new solution) unless you change the project name and add to the current solution.第一个常见问题是 IDE 会引导您创建新项目,而不是将新文件(.java、.py、.cpp、.c)添加到现有解决方案(默认情况下它会创建新解决方案),除非您更改项目名称并添加到当前的解决方案中。 This problem occurs for Python, java, c#, C++ and C project folders. Python、java、c#、C++ 和 C 项目文件夹会出现此问题。

The new developer selecting "new>project>project name and changing the solution directory to "use same solution" still creates a new "project" in the same solution space, but not in the same directory space as the current user interface file or command line file which still leads to problems with "package not found" errors when building and running the project or solution. This is why the above coding suggestions to importing packages, classes, methods and functions only work (and thus don't answer the question) when the "library" file or "separate behavior" file is not only in the same solution directory path, but also in the same "user interface" or "command shell" application directory space. This does does not happen when you add another project using the new>project>project type commands of the IDE. The problem here is the new project is stored in a different directory than the existing Client or User interface code files. To create a new "file" in the same project space rather th新开发者选择“新建>项目>项目名称”并将解决方案目录更改为“使用相同的解决方案”仍会在同一解决方案空间中创建一个新的“项目”,但与当前用户界面文件或命令不在同一目录空间中line 文件,在构建和运行项目或解决方案时仍然会导致“找不到包”错误的问题。这就是为什么上述导入包、类、方法和函数的编码建议仅有效(因此不回答问题) 当“库”文件或“单独行为”文件不仅在同一个解决方案目录路径中,而且在同一个“用户界面”或“命令外壳”应用程序目录空间中时。添加另一个时不会发生这种情况项目使用 IDE 的 new>project>project type 命令。这里的问题是新项目存储在与现有客户端或用户界面代码文件不同的目录中。在同一项目空间中创建一个新的“文件”而不是日an new project the beginner needs to do the following that Microsoft won't do for you and even misleads you away from the intuitively obvious by default.一个新项目初学者需要做以下微软不会为你做的事情,甚至默认情况下会误导你远离直观的显而易见的事情。

  1. Select the "application" you want to import the new behavior into (from another file)选择要将新行为导入的“应用程序”(从另一个文件)
  2. Select project>add new item选择项目>添加新项目
  3. Select the "program file template type" such as filetype.py, filetype.java, filetype.c, filetype.cpp, filetype.C#, etc. or a library class file type (something other than startup file options you see when you create a new application project or create a new library project).选择“程序文件模板类型”,例如 filetype.py、filetype.java、filetype.c、filetype.cpp、filetype.C# 等或库类文件类型(创建时看到的启动文件选项以外的其他内容)一个新的应用程序项目或创建一个新的库项目)。
  4. A new file name with default name is created in your project.在您的项目中创建一个具有默认名称的新文件名。
  5. Change the default name of the file to something like library.py or façade.java, etc.将文件的默认名称更改为 library.py 或 façade.java 等。

NOW the code recommendations to import libraries or using namespaces will work as described in the comments above and you don't have to change path statements or change solutions paths and solution names that Microsoft won't let you change easily (ie you can change the filenames or project names but the IDE won't automatically change the project path or the solution path names).现在,导入库或使用命名空间的代码建议将按照上述注释中的描述工作,您不必更改路径语句或更改 Microsoft 不允许您轻松更改的解决方案路径和解决方案名称(即您可以更改文件名或项目名称,但 IDE 不会自动更改项目路径或解决方案路径名称)。

The following is a Python example but works similar for C#, java, or C/C++ using the includes, namespaces or using code commands appropriate to each language to find code in other classes/projects in the SAME DIRECTORY SPACE.下面是一个 Python 示例,但对于 C#、java 或 C/C++ 的工作方式类似,使用包含、命名空间或使用适合每种语言的代码命令在同一目录空间中的其他类/项目中查找代码。

The application file "hello world" importing from other code files in the same directory.从同一目录中的其他代码文件导入的应用程序文件“hello world”。

Note the python white space delimiters are not going to space correctly in this stackoverflow comment editor:请注意,python 空格分隔符在此 stackoverflow 注释编辑器中不会正确空格:

print ("test")

from CIXMPythonFacade import ClassA

c1=ClassA
c1.methodA()

from CIXMPythonFacade import functionA 

functionA()


class ClassName(object): 
         def __init__(object, parameter):
         object.parameter = value

The library file or "façade" file containing classes, methods or functions you want to import.包含要导入的类、方法或函数的库文件或“外观”文件。

class class1(object):
    """description of class"""

class ClassA(object):
    print ("test2")
    def methodA():
        print ("test3")

def functionA ():
    print ("test4")
    return (0)


pass

NOW how do you actually solve the mess that the IDE leads you into?现在,您实际上如何解决 IDE 导致您陷入的混乱局面? To import code from another file in the same directory space you add a reference to it.要从同一目录空间中的另一个文件导入代码,请添加对它的引用。

  1. Select the application file选择申请文件
  2. Select Project>add reference选择项目>添加引用
  3. Choose the filename visible with the right directory path (check it)选择具有正确目录路径的可见文件名(检查它)
  4. The reference is now available to the interpreter, the code checker and/or the compiler.该引用现在可供解释器、代码检查器和/或编译器使用。

OK so now that you have this problem solved, how do you really link two separate projects together in the same solution space?好的,既然您已经解决了这个问题,那么您如何真正将同一解决方案空间中的两个独立项目链接在一起?

  1. You have to go to both the indexer or "intellisense" options and the compiler/interpreter and physically check or change/add the directory path statements if they are something other than what points to your "second" project or solution space.您必须同时使用索引器或“智能感知”选项以及编译器/解释器,并物理检查或更改/添加目录路径语句,如果它们不是指向“第二”项目或解决方案空间的内容。 When you do the path changes or change the path variables to your workspace and to the specific locations of the projects which are different directory spaces the compiler and the code analyzer can then find these libraries, headers.h, namespaces, project or file locations.当您更改路径或将路径变量更改为您的工作区和项目的特定位置时,编译器和代码分析器可以找到这些库、headers.h、命名空间、项目或文件位置。
  2. To remove old projects you created by mistake it is even worse.删除您错误创建的旧项目更糟。 You have to exit the Visual Studio IDE, open windows explorer, go to the workspace directory ...documents\\visualstudio xxx\\solutionname\\packagename select the file or folder, right click and "delete" file or folder.您必须退出 Visual Studio IDE,打开 Windows 资源管理器,转到工作区目录 ...documents\\visualstudio xxx\\solutionname\\packagename 选择文件或文件夹,右键单击并“删除”文件或文件夹。
  3. When you re-enter the IDE and select open solution or open package/solution, the old files and solution/package names are gone as are their misleading path statements which fools the compiler and code analyzer to look at the old directory even though you changed the filename and changed the project name, it does not change the directory path with it.当您重新进入 IDE 并选择打开解决方案或打开包/解决方案时,旧文件和解决方案/包名称以及它们误导性的路径语句都消失了,即使您已更改,它们也会欺骗编译器和代码分析器查看旧目录文件名并更改了项目名称,它不会随之更改目录路径。

Microsoft really, really needs to fix these problem so you can intuitively create what most people want to create as new files in the same directories and remove solutions by selecting them and deleting them from the IDE. Microsoft 真的、真的需要解决这些问题,以便您可以直观地在同一目录中创建大多数人想要创建的新文件,并通过选择解决方案并将其从 IDE 中删除来删除解决方案。 Beginners get so frustrated with directory path statements so flexible for seasoned developers, but so unfair to new developers in their defaults.初学者对目录路径声明对经验丰富的开发人员如此灵活感到非常沮丧,但对新开发人员的默认设置如此不公平。

Hope this really helps you new guys and stops seasoned developers from giving you the wrong answers that don't work for you.希望这真的可以帮助你们新人,并阻止经验丰富的开发人员给你不适合你的错误答案。 They assume you already understand path statements and just want to type the right code...which is also why the tunnel in on trying to correct your code but does not help you fix the problem.他们假设您已经了解路径语句并且只想输入正确的代码......这也是为什么尝试更正代码但无法帮助您解决问题的原因。 This is probably the most common problem continually described on stackoverflow with wrong answers that don't work for new programmers.这可能是 stackoverflow 上不断描述的最常见的问题,错误答案对新程序员不起作用。

The first step is to make P2 reference P1 by doing the following第一步是通过执行以下操作使 P2 引用 P1

  • Right Click on the project and select "Add Reference"右键单击项目并选择“添加引用”
  • Go to the Projects Tab转到项目选项卡
  • Select P1 and hit OK选择 P1 并点击确定

Next you'll need to make sure that the classes in P1 are accessible to P2.接下来,您需要确保 P1 中的类可供 P2 访问。 The easiest way is to make them public .最简单的方法是将它们public

public class MyType { ... }

Now you should be able to use them in P2 via their fully qualified name.现在您应该能够通过它们的完全限定名称在 P2 中使用它们。 Assuming the namespace of P1 is Project1 then the following would work假设 P1 的命名空间是 Project1 那么下面的工作

Project1.MyType obj = new Project1.MyType();

The preferred way though is to add a using for Project1 so you can use the types without qualification不过,首选方法是为Project1添加 using,以便您无需限定即可使用类型

using Project1;
...

public void Example() {
  MyType obj = new MyType();
}

If you have two projects in one solution folder.Just add the Reference of the Project into another.using the Namespace you can get the classes.如果您在一个解决方案文件夹中有两个项目。只需将项目的引用添加到另一个。使用命名空间,您可以获得类。 While Creating the object for that the requried class.在为所需的类创建对象时。 Call the Method which you want.调用你想要的方法。

FirstProject:第一个项目:

class FirstClass()
{
   public string Name()
   {
      return "James";
   }
}

Here add reference to the Second Project这里添加对第二个项目的引用

SecondProject:第二项目:

class SeccondClass
{
    FirstProject.FirstClass obj=new FirstProject.FirstClass();
    obj.Name();
}

In project P1 make the class public (if it isn't already).在项目 P1 中,将班级设为公开(如果尚未公开)。 Then add a project reference (rather than a file reference, a mistake I've come across occasionally) to P2.然后向 P2 添加项目引用(而不是文件引用,这是我偶尔遇到的错误)。 Add a using statement in P2 at the correct place and start using the class from P1.在 P2 中的正确位置添加 using 语句并开始使用 P1 中的类。

(To mention this: The alternative to making the class public would be to make P2 a friend to P1. This is, however, unlikely to be the answer you are after as it would have some consequences. So stick with the above suggestion.) (提一下:公开课程的另一种方法是让 P2 成为 P1 的朋友。然而,这不太可能是你想要的答案,因为它会产生一些后果。所以坚持上面的建议。)

Say your class in project 2 is called MyClass.假设您在项目 2 中的班级称为 MyClass。

Obviously, first reference your project 2 under references in project 1 then显然,首先在项目 1 中的引用下引用您的项目 2,然后

using namespaceOfProject2;

// for the class calling bit:

namespaceOfProject2.MyClass project2Class = new namespaceOfProject2.MyClass();

so whenever you want to reference that class you type project2Class.所以每当你想引用那个类时,你输入 project2Class。 Plus make sure that class is public too.另外,请确保该课程也是公开的。

I had an issue with different target frameworks.我遇到了不同目标框架的问题。

I was doing everything right, but just couldn't use the reference in P2.我做的一切都正确,但无法使用 P2 中的参考。 After I set the same target framework for P1 and P2, it worked like a charm.在我为 P1 和 P2 设置相同的目标框架后,它就像一个魅力。

Hope it will help someone希望它会帮助某人

To provide another much simpler solution:-提供另一个更简单的解决方案:-

  1. Within the project, right click and select "Add -> Existing"在项目中,右键单击并选择“添加 -> 现有”
  2. Navigate to the class file in the adjacent project.导航到相邻项目中的类文件。
  3. The Add button is also a dropdown, click the dropdown and select添加按钮也是一个下拉菜单,点击下拉菜单并选择

"Add as link" “添加为链接”

Thats it.就是这样。

You will need to right click your project and select add -> Reference... -> Projects and tick the project you would like to reference.您需要右键单击您的项目并选择add -> Reference... -> Projects并勾选您想要引用的项目。

The result of this should show the referenced project under the references section of your project tree.这样做的结果应该在项目树的引用部分下显示引用的项目。

A common use case involves adding a testing framework, say, a NUnit project to your solution.一个常见用例涉及向您的解决方案添加测试框架,例如 NUnit 项目。 This NUnit project would then need to reference your main project.这个 NUnit 项目然后需要引用您的主项目。 In order to do this, the steps are slightly different: You will need to right click your NUnit project and select add -> Project Reference... -> Projects and tick the project you would like to reference.为此,步骤略有不同:您需要右键单击您的 NUnit 项目并选择add -> Project Reference... -> Projects并勾选您想要引用的项目。

The result of this should show the referenced project under the "Projects" section of your NUnit project tree.这样做的结果应该在 NUnit 项目树的“项目”部分下显示引用的项目。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM