Make reference to C# code from multiple projects

后端 未结 4 1429
走了就别回头了
走了就别回头了 2020-12-19 04:08

I have a .cs file full of C# code I keep reusing in multiple projects.

Right now I\'m including it in these projects by copying and pasting the code int

相关标签:
4条回答
  • 2020-12-19 04:29

    Or,

    • Right-Click on the project in Solution explorer
    • Select Add Existing Item
    • Browse to the .cs file in another project, and Single-click to select the file
    • Click the down-arrow button to the right of Add and select Add as Link

    You now have one source file referenced by two projects but it has the namespace you gave it in the first project which might not be ideal.

    The best way of organizing that is to as the two other answers have suggested, put common code in a class library so it has a namespace of MyClassLibrary rather than SomeOtherProject. It saves a larger dll being copied which doesn't matter much until you come to develop for something small like Windows Phone. Or change the namespace of common code to be Me.Common in all your apps - it doesn't really matter which one is the original, you can edit it from any project that references it.

    Check that Source Control isn't a problem.

    0 讨论(0)
  • 2020-12-19 04:35

    Create a Class Library, add the file, build the project, and reference the DLL created from the build. Add the using statement to each file that will reference it. Also if it errors and the DLL is in the Project you and Right Click on the object -> Resolve and it will add the using for you.

    0 讨论(0)
  • 2020-12-19 04:37

    Put the code into a separate class library project and reference that in your other projects.

    0 讨论(0)
  • 2020-12-19 04:51

    I wrote an app that automates adding a code as a link, handy for projects that reuse a lot of code and change a bit. It's at https://github.com/CADbloke/CodeLinker

    or

    Don't be afraid to edit XML .csproj files. For instance, this works ...

    <Compile Include="$(Codez)\z.Libraries\diff-match-patch\DiffMatchPatch\**\*.cs"
    Exclude="NotThisOne.cs;**\NotThisFolderWith\This*.cs">
    <Link>Libs\%(RecursiveDir)%(Filename)%(Extension)</Link>
    </Compile>
    

    ...and will give you all the C# files from the source folder, and subfolders, as linked files in your destination project.

    • $(Codez) is a Windows Environment Variable I use on my PCs.
    • I also could have used *.* at the end instead of *.cs.
    • This is one of those things Visual Studio might break on you, adding a file into the folder full of wildcard-linked files may break them out to separate entries. Or not. Depends on the wind.
    0 讨论(0)
提交回复
热议问题