rename a function in C#

2019-08-30 23:24发布

问题:

is there a way in C# to rename System.Console.WriteLine so that in my C#/console/visual studio program I could write

printf("hello");
//instead of 
System.Console.WriteLine("Hello");   //??

What would this be, a class? a namespace? Do I do this in the header or inside of main?

回答1:

Your target looks strange and there is no way to do this in c#. Alternatively you can add a method in a class and use it.

private static void printf(string value)
{
    System.Console.WriteLine(value);
}

Note: above method works only in the class which you write the above method.



回答2:

Write a wrapper:

public string printf(string theString)
{
  System.Console.WriteLine(theString);
}


回答3:

You can use code snippets: http://msdn.microsoft.com/en-us/library/ms165392.aspx You can always write your own.

I think Visual Studio has a few by default, like writing cw and hitting TAB to get System.Console.WriteLine

Edit Here is a list of the default VS code snippets: http://msdn.microsoft.com/en-us/library/z41h7fat(v=vs.90).aspx

You can also use ReSharper to easily write your own, like this one I did for dw -> Debug.WriteLine



回答4:

You can wrap your code in a function, for example

public void Printf(string message)
{
      System.Console.Writeline(message);
}

It is not recommended that you start your function with a lowercase letter (for example printf) as this is not a c# convention.



回答5:

First of all , do this is not a good practice.

But programatically this is achievable by wrting Wraps.

public string printf(string urstring)
{ 
System.Console.WriteLine(urstring);
}


回答6:

C# 6.0 Simplifies this by using static directives. Now instead of typing all of this: System.Console.WriteLine(...), you could simply type: WriteLine(...)

using static System.Console;

namespace DemoApp
{
    class Program
    {
        static void Main(string[] args)
        {
            WriteLine("Hello");
        }
    }
}

More Info: C# : How C# 6.0 Simplifies, Clarifies and Condenses Your Code



回答7:

If you want to get fancy you can do this:

static class DemoUtil
{
    public static void Print(this object self)
    {
        Console.WriteLine(self);
    }

    public static void Print(this string self)
    {
        Console.WriteLine(self);
    }
}

Then it would become:

"hello".Print();
12345.Print();
Math.Sin(0.345345).Print();
DateTime.Now.Print();

And so on. I don't recommend this for production code - but I do use this for my test code. I'm lazy.