问题
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:
- If you have a Console Application project in your solution, use Console.WriteLine(), as usual.
- 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