rename a function in C#

2019-08-30 23:27发布

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?

7条回答
Anthone
2楼-- · 2019-08-30 23:44

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.

查看更多
小情绪 Triste *
3楼-- · 2019-08-30 23:44

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);
}
查看更多
对你真心纯属浪费
4楼-- · 2019-08-30 23:44

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.

查看更多
倾城 Initia
5楼-- · 2019-08-30 23:45

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

enter image description here

查看更多
相关推荐>>
6楼-- · 2019-08-30 23:51

Write a wrapper:

public string printf(string theString)
{
  System.Console.WriteLine(theString);
}
查看更多
劳资没心,怎么记你
7楼-- · 2019-08-30 23:57

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

enter image description here

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

查看更多
登录 后发表回答