Possible to output to console from within a class library C#?

做~自己de王妃 提交于 2020-01-01 05:04:49

问题


Is it possible to output values to the console from within a class library?

For example

 Console App -> calls method in -> assembly > function

Is it possible to write a console.out method in the function of the assembly?

I know in web its possible to get the httpcontext, and do a response.write.


回答1:


Yup, Console.WriteLine etc will work just fine in a class library... but there's no guarantee that anything is listening to the console. If you use it from a WinForms app or a web app, that output may well go absolutely nowhere...

Have you thought of using a logging library such as log4net instead?




回答2:


It depends on what type of application is going to use your class library. If it is used in a console application, then the output will be printed to the console. If it is a WinForms, Windows Service or ASP.NET application the output will be ignored.




回答3:


Sure it is, just use System.Console.Write...




回答4:


Sure if the library client is a Console app, just call Console.WriteLine("") with your messages.

If you do not have a console based client and you want to open a Console for your own use then you need to use P/Invoke to call ConsoleAlloc. See here for some help with the P/Invoke declaration.

Having said that I must also point out that writing to the console from a Class library is decidedly bad design and you should consider using the dot net tracing/logging mechanism instead (Peruse the Microsoft documentation on System.Diagnostics)




回答5:


  1. If you have a Console Application project in your solution, use Console.WriteLine(), as usual.
  2. Otherwise, if you have a Class Library project, use System.Diagnostics.Debug.WriteLine().

The bad news: - Your texts will be in the middle of all the lines in Output. - You'll have to search them. I recommend you to select all the text in the Output and paste on a Notepad. It will be easier to find what you're looking for.

The good news: - Your texts wil be alone in their lines. Only the result from your command System.Diagnostics.Debug.WriteLine().



来源:https://stackoverflow.com/questions/1288294/possible-to-output-to-console-from-within-a-class-library-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!