Hidden Features of C#? [closed]

2018-12-31 01:48发布

This came to my mind after I learned the following from this question:

where T : struct

We, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc.

Some of us even mastered the stuff like Generics, anonymous types, lambdas, LINQ, ...

But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?

Here are the revealed features so far:


Keywords

Attributes

Syntax

Language Features

Visual Studio Features

Framework

Methods and Properties

Tips & Tricks

  • Nice method for event handlers by Andreas H.R. Nilsson
  • Uppercase comparisons by John
  • Access anonymous types without reflection by dp
  • A quick way to lazily instantiate collection properties by Will
  • JavaScript-like anonymous inline-functions by roosteronacid

Other

30条回答
唯独是你
2楼-- · 2018-12-31 02:10

From Rick Strahl:

You can chain the ?? operator so that you can do a bunch of null comparisons.

string result = value1 ?? value2 ?? value3 ?? String.Empty;
查看更多
临风纵饮
3楼-- · 2018-12-31 02:11

This isn't C# per se, but I haven't seen anyone who really uses System.IO.Path.Combine() to the extent that they should. In fact, the whole Path class is really useful, but no one uses it!

I'm willing to bet that every production app has the following code, even though it shouldn't:

string path = dir + "\\" + fileName;
查看更多
何处买醉
4楼-- · 2018-12-31 02:11

Two things I like are Automatic properties so you can collapse your code down even further:

private string _name;
public string Name
{
    get
    {
        return _name;
    }
    set
    {
        _name = value;
    }
}

becomes

public string Name { get; set;}

Also object initializers:

Employee emp = new Employee();
emp.Name = "John Smith";
emp.StartDate = DateTime.Now();

becomes

Employee emp = new Employee {Name="John Smith", StartDate=DateTime.Now()}
查看更多
倾城一夜雪
5楼-- · 2018-12-31 02:12

I think one of the most under-appreciated and lesser-known features of C# (.NET 3.5) are Expression Trees, especially when combined with Generics and Lambdas. This is an approach to API creation that newer libraries like NInject and Moq are using.

For example, let's say that I want to register a method with an API and that API needs to get the method name

Given this class:

public class MyClass
{
     public void SomeMethod() { /* Do Something */ }
}

Before, it was very common to see developers do this with strings and types (or something else largely string-based):

RegisterMethod(typeof(MyClass), "SomeMethod");

Well, that sucks because of the lack of strong-typing. What if I rename "SomeMethod"? Now, in 3.5 however, I can do this in a strongly-typed fashion:

RegisterMethod<MyClass>(cl => cl.SomeMethod());

In which the RegisterMethod class uses Expression<Action<T>> like this:

void RegisterMethod<T>(Expression<Action<T>> action) where T : class
{
    var expression = (action.Body as MethodCallExpression);

    if (expression != null)
    {
        // TODO: Register method
        Console.WriteLine(expression.Method.Name);
    }
}

This is one big reason that I'm in love with Lambdas and Expression Trees right now.

查看更多
余生请多指教
6楼-- · 2018-12-31 02:12

I tend to find that most C# developers don't know about 'nullable' types. Basically, primitives that can have a null value.

double? num1 = null; 
double num2 = num1 ?? -100;

Set a nullable double, num1, to null, then set a regular double, num2, to num1 or -100 if num1 was null.

http://msdn.microsoft.com/en-us/library/1t3y8s4s(VS.80).aspx

one more thing about Nullable type:

DateTime? tmp = new DateTime();
tmp = null;
return tmp.ToString();

it is return String.Empty. Check this link for more details

查看更多
其实,你不懂
7楼-- · 2018-12-31 02:12

Unions (the C++ shared memory kind) in pure, safe C#

Without resorting to unsafe mode and pointers, you can have class members share memory space in a class/struct. Given the following class:

[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;
}

You can modify the values of the byte fields by manipulating the Int32 field and vice-versa. For example, this program:

    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);
    }

Outputs this:

2147483647
FF FF FF 7F
65535

just add using System.Runtime.InteropServices;

查看更多
登录 后发表回答