test it~~

http://blog.csdn.net/lindexi_gd/article/details/79617425

This article will tell you about the technology that few people will find in C#. Even an old driver who has worked for many years may not know it. If you think I am lying to you, then please take a look at the following


Because of the help of C# in Microsoft, it has been very simple to use now. For more than 10 years, very few people know what Microsoft has done. I found a lot of great gods blogs on the Internet, and then chatted with many great gods, and learned some technology, so I will say it here. If you see technology that is not in this blog, please let me know.

Unlimited Judgment Empty

In C# 6.0, you can use the ??judgment empty, then you can use the following code

            var v1 = "123";
            string v2 = null;
            string v3 = null;

            var v = v1 ?? v2 ?? v3;

Virtually unlimited use??

using omits long definitions

For example, there is this code, which uses a lot of List, which has a lot of definitions

var foo =
                new System.Collections.Generic.Dictionary<
                    System.Collections.Generic.List<System.Collections.Generic.List<string>>, string>();

It can be seen that a lot of code needs to be written. If this value is used as a parameter, it is terrible.

An easy way is to use

using HvcnrclHnlfk=System.Collections.Generic.Dictionary<System.Collections.Generic.List<System.Collections.Generic.List<string>>,string>;

, all definitions in this file can be replaced by the usingfollowing values.

var foo = new HvcnrclHnlfk();

so big

In fact, I'm a little embarrassed, it seems that everyone knows what I just said, so I'm going to start writing that everyone knows very little.

          Func<string,string, EventHandler> foo = (x, y) => (s, e) =>
            {
                var button = (Button) s;
                button.Left = x;
                button.Top = y;
            };

            Button1.Click += foo(0, -1);

Take a look to see what this definition can do

type of conflict

If you encounter the same type in two namespaces, in many cases, the namespace is written in full.

var webControl = new System.Web.UI.WebControls.Control();
var formControl = new System.Windows.Forms.Control();

If you use these two controls frequently, you need to write space, there is a lot of code, but Microsoft has given a pit, you can use this without writing space

using web = System.Web.UI.WebControls;
using win = System.Windows.Forms;

web::Control webControl = new web::Control();
win::Control formControl = new win::Control();

See: https://stackoverflow.com/a/9099/6116637

extern alias

If two dlls are used, both with the same namespace and type, how to use the specified library

//a.dll

namespace F
{
    public class Foo
    {

    }
}

//b.dll

namespace F
{
    public class Foo
    {

    }
}

Then you can use extern alias

See also: C# uses extern alias to resolve the same type full name in two assemblies - fresky - Blog Park

string

We have seen C# 6.0 $, can we @go with it?

            var str = "kktpqfThiq";
            string foo = $@"换行
{str}";

Pay attention to the order of the two, which in turn tells you that the code cannot be written like this

Expression tree get function name

Define a class, and get the function name from the class through the expression tree below

    class Foo
    {
        public void KzcSevfio()
        {
        }
    }
       static void Main(string[] args)
        {
            GetMethodName<Foo>(foo => foo.KzcSevfio());
        }

        private static void GetMethodName<T>(Expression<Action<T>> action) where T : class
        {
            if (action.Body is MethodCallExpression expression)
            {
                Console.WriteLine(expression.Method.Name);
            }
        }

So you can get the name of the function

special keywords

In fact, the following keywords are undocumented, and may only be known by rubbish Microsoft compilers

__makeref

__reftype

__refvalue

__arglist

But in C# 7.2, you can use other keywords to do some, please see my C# 7.0 blog for details

DebuggerDisplay

If you want to move the mouse to the variable to display its information when debugging, you can override the ToString of the class

    public sealed class Foo
    {
        public int Count { get; set; }

        public override string ToString()
        {
            return Count.ToString();
        }
    }

But what if ToString is used elsewhere?

Trash Microsoft tells everyone to use the DebuggerDisplay feature

    [DebuggerDisplay("{DebuggerDisplay}")]
    public sealed class Foo
    {
        public int Count { get; set; }

        private string DebuggerDisplay => $"(count {Count})";
    }

He can use private properties and fields, and the usage is very simple

参见Using the DebuggerDisplay Attribute

Use Unions (same as C++)

If you see that C++ can use inline, don't say C# doesn't, you can actually use FieldOffset, see below

[StructLayout(LayoutKind.Explicit)]
public class A
{
    [FieldOffset(0)]
    public byte One;

    [FieldOffset(1)]
    public byte Two;

    [FieldOffset(2)]
    public byte Three;

    [FieldOffset(3)]
    public byte Four;

    [FieldOffset(0)]
    public int Int32;
}

At this time, the variable is defined int, and modifying it is to modify the other three

     static void Main(string[] args)
    {
        A a = new A { Int32 = int.MaxValue };

        Console.WriteLine(a.Int32);
        Console.WriteLine("{0:X} {1:X} {2:X} {3:X}", a.One, a.Two, a.Three, a.Four);

        a.Four = 0;
        a.Three = 0;
        Console.WriteLine(a.Int32);
    }

will output

2147483647
FF FF FF 7F
65535

interface default method

You can actually use default methods for interfaces, the way you use them

public static void Foo(this IF1 foo)
{
     //实际上大家也看到是如何定义
}

number format

string format = "000;-#;(0)";

string pos = 1.ToString(format);     // 001
string neg = (-1).ToString(format);  // -1
string zer = 0.ToString(format);     // (0)

See also: Custom Number Format Strings

stackalloc

In fact, many people don't know this, this is unsafe code, requesting space from the stack

int* block = stackalloc int[100]; 

See also: stackalloc

call stack

If you need to get the stack of the calling method, you can use the method of this article

  class Program
    {
        static void Main(string[] args)
        {
            var foo = new Foo();
            foo.F1();
        }
    }

    public sealed class Foo
    {
        public void F1()
        {
            F2();
        }

        void F2()
        {
            var stackTrace = new StackTrace();
            var n = stackTrace.FrameCount;
            for (int i = 0; i < n; i++)
            {
                Console.WriteLine(stackTrace.GetFrame(i).GetMethod().Name);
            }
        }
    }

output

F2
F1

See also: WPF Determining Calling Method Stack

specify compilation

If using Conditional can make the code not used in specified conditions, I wrote this code, and F2 will not be used under Release

    public sealed class Foo
    {
        public Foo F1()
        {
            Console.WriteLine("进入F1");
            return this;
        }

        [Conditional("DEBUG")]
        public void F2()
        {
            Console.WriteLine("F2");
        }
    }

Just let the code run

        static void Main(string[] args)
        {
            var foo = new Foo();
            foo.F1();
            foo.F2();
        }

What is the result, as we all know, the output in Debug and Release is not the same. But how can it be so simple here, please see what this code outputs

     static void Main(string[] args)
        {
            var foo = new Foo();
            foo.F1().F2();
        }

In fact, nothing will be output under Release, and F1 will not be executed

true judgment

Write the damn code below

            var foo = new Foo(10);

            if (foo)
            {
                Console.WriteLine("我的类没有继承 bool ,居然可以这样写");
            }

That's right, Foo doesn't inherit bool, but it can be written like this

In fact, it is to rewrite true, please see the code

    public class Foo
    {
        public Foo(int value)
        {
            _count = value;
        }

        private readonly int _count;

        public static bool operator true(Foo mt)
        {
            return mt._count > 0;
        }

        public static bool operator false(Foo mt)
        {
            return mt._count < 0;
        }
    }

Do you think a lot of people write this way, let's show you a technology that few people know about, thanks walterlv

await any type

await "林德熙逗比";

await "不告诉你";

This code can be compiled, but only on my device, and after reading this blog , maybe you can also compile on your device

Use Chinese for variable names

In fact, all Unicode is supported in C#, so it is also possible to use Chinese for variable names, and special characters can be used

        public string H\u00e5rføner()
        {
            return "可以编译";
        }

Creative Commons License
This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 4.0 International License. You are welcome to reprint, use, and republish, but be sure to keep the article's signature Lin Dexi (including the link: http://blog.csdn.net/lindexi_gd ), and must not be used for commercial purposes. Works modified based on this article must be released with the same license. If you have any questions, please contact me .

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325455896&siteId=291194637