How do I compile C# code as a library instead of a

2019-02-16 21:27发布

I have a C# console application in Visual Studio 2010. It has a Main() method as well as a bunch of utility classes. I'd like those utility classes to be available to other solutions. From reading online it seems that I need to compile it as a Class Library (DLL). So here's what I did:

  • Went in Visual Studio to "Project > [ProjectName] Properties > Application" and changed "Output type" from "Console Application" to "Class Library"
  • Rebuilt; ProjectName.dll was created in bin/Debug.
  • Created a new Console Application
  • Solution Explorer > Add Reference > browse to ProjectName.DLL, select it.

However, neither IntelliSense nor the Object Browser could find the classes inside that DLL.

I tried recompiling several different Console Applications as Class Libraries and got the same result. I also noticed that it works if I initially create the solution as a Class Library, but not if I convert it to one later.

Any tips?

5条回答
孤傲高冷的网名
2楼-- · 2019-02-16 22:07

Make sure that the classes in your dll project are public.

查看更多
爱情/是我丢掉的垃圾
3楼-- · 2019-02-16 22:15

You do not need to build it as a dll. VS 2010 (and IIRC 2008) allow referencing exe assemblies. All you need is for they relevant types to be declared public - top-level classes defualt to internal if you don't add a specifier.

查看更多
劳资没心,怎么记你
4楼-- · 2019-02-16 22:18

You can switch output type to Class library in project properties as well - then you will have an output as dll instead exe file

查看更多
三岁会撩人
5楼-- · 2019-02-16 22:20

What I've always done (since this is what you do with C++ static libraries, which is what I normally use - though I think it has some advantages for C# too) is add the class library's project to the solution, then add a reference to it in the project (or projects) that uses it. When you go to add a reference, the list of potential references includes items from the solution, so it should be fairly obvious what to do. You should then get intellisense for your library.

One advantage of doing things this way is that if you need to edit files in the library project, it's very straightforward because they are close to hand, and the project then gets rebuilt automatically when you compile the solution.

查看更多
走好不送
6楼-- · 2019-02-16 22:24

At first, from the point of view of managed libraries it does not matter what kind of Output type is your managed library. I mean that you can successfully reference ConsoleApplication1.exe from ConsoleApplication2.exe project (so you have no reason to convert ConsoleApplication1.exe to ConsoleApplication1.dll).

At second, I've tried to reproduce your situation, but... without effect. My VS displays types/methods from ConsoleApplication1.dll. One reason I can suppose is that you have forgotten to set visibility modifier (public keyword) for your utility classes.

查看更多
登录 后发表回答