在我从这个问题中了解到以下内容后,我想到了这一点:

where T : struct

我们,C#开发人员,都知道C#的基础知识。我指的是声明、条件、循环、运算符等。

我们中的一些人甚至掌握了Generics、匿名类型、lambdas、LINQ等等。。。

但是,即使是C#的粉丝、瘾君子和专家也几乎不知道C#最隐藏的功能或技巧是什么?

以下是迄今为止揭示的功能:

关键词

迈克尔·斯图姆的产量Michael Stum的varkokos的using()语句kokos只读由Mike Stone作者:Ed Swangren由Rocketpants改进因死亡而违约全球::由pzycomanAlexCuse的using()块Jakubšturc的挥发性Jakubšturc的外部别名

属性

Michael Stum的DefaultValueAttributeDannySmurf的ObsoleteAttribute调试器DisplayAttribute(按Stu)bdukes提供的DebuggerBrowseble和DebuggerStepThroughmarxidad的ThreadStaticAttributeMartin Clarke的FlagsAttributeAndrewBurns的ConditionalAttribute

语法

?? kokos的(合并空值)运算符Nick Berardi的数字标记其中T:Lars Mæhlum的新Keith的隐式泛型Keith的单参数lambdas基思汽车财产Keith的命名空间别名Patrick的带@的逐字字符串文字按lfoost列出的枚举值@marxidad的variableamesmarxidad的事件运算符由Portman设置字符串括号格式xanadot的属性访问器可访问性修饰符JasonS的条件(三元)运算符(?:)Binoj Antony检查和未检查操作员Flory的隐式和显式运算符

语言功能

Brad Barker的可空类型Keith的匿名类型__由Judah Himango制作的makeref __reftype __refvaluelomaxx的对象初始化器达科他州David的字符串格式marxidad的扩展方法Jon Erickson的部分方法John Asbeck的预处理器指令Robert Durgin的DEBUG预处理器指令SefBkn导致操作员过载通过chakrit推断类型Rob Gough将布尔运算符提升到下一级通过Roman Boiko将值类型变量作为不带装箱的接口传递由Roman Boiko编程确定声明的变量类型Chris的静态构造器使用LINQ by roosteronacid更容易进行眼睛/精简ORM映射__Zac Bowling的arglist

Visual Studio功能

Himadri在编辑器中选择文本块DannySmurf的片段

框架

KiwiCastard的TransactionScopeKiwiAstard的从属事务IainMH的<T>可为空迪亚戈的Mutex按ageektrapped列出的System.IO.PathJuan Manuel的WeakReference

方法和财产

KiwiAstard的String.IsNullOrEmpty()方法KiwiCastard的List.ForEach()方法Will Dean的BeginInvoke()、EndInvoke(()方法Nullable<T>。HasValue和Nullable<T>。Rismo的Value财产John Sheehan的GetValueOrDefault方法

提示和技巧

Andreas H.R.Nilsson的事件处理程序的好方法John的大写比较访问匿名类型而不通过dp进行反射Will延迟实例化集合财产的快速方法chosteronacid提供的类似JavaScript的匿名内联函数

另外

kokos的netmodulesDuncan Smart的LINQBridgeJoel Coehorn的并行扩展


当前回答

IOobservable怎么样?

几乎每个人都知道IEnumerable,但他们的数学对偶似乎是未知的IOobservable。可能是因为它是.NET4。

它所做的不是拉取信息(像可枚举的),而是将信息推送给观察者的订阅者。

与Rx扩展一起,它将改变我们处理事件的方式。为了说明它有多强大,请查看这里的一个非常简短的示例。

其他回答

我发现编译器在对外部变量的使用进行编码时遇到了什么样的麻烦,真是难以置信:

string output = "helo world!";
Action action = () => Console.WriteLine(output);
output = "hello!";
action();

这实际上是打印hello!。为什么?因为编译器为委托创建了一个嵌套类,所有外部变量都有公共字段,并在每次调用委托之前插入设置代码:)下面是代码“reflected”:

Action action;
<>c__DisplayClass1 CS$<>8__locals2;
CS$<>8__locals2 = new <>c__DisplayClass1();
CS$<>8__locals2.output = "helo world!";
action = new Action(CS$<>8__locals2.<Main>b__0);
CS$<>8__locals2.output = "hello!";
action();

我觉得很酷。

固定/C#中指针的力量-这个主题太大了,但我只概述一些简单的事情。

在C中,我们有装载结构的设施,如。。。

struct cType{
   char type[4];
   int  size;
   char name[50];
   char email[100];
}

cType myType;
fread(file, &mType, sizeof(mType));

我们可以在“unsafe”方法中使用fixed关键字来读取字节数组对齐的结构。

[Layout(LayoutKind.Sequential, Pack=1)]
public unsafe class CType{
    public fixed byte type[4];
    public int size;
    public fixed byte name[50];
    public fixed byte email[100];
}

方法1(从字节缓冲区中的常规流读取,并将字节数组映射到结构的各个字节)

CType mType = new CType();
byte[] buffer = new byte[Marshal.SizeOf(CType)];
stream.Read(buffer,0,buffer.Length);
// you can map your buffer back to your struct...
fixed(CType* sp = &mType)
{
    byte* bsp = (byte*) sp;
    fixed(byte* bp = &buffer)
    {
         for(int i=0;i<buffer.Length;i++)
         {
             (*bsp) = (*bp);
             bsp++;bp++;
         }
    }
}

方法2,您可以将Win32 User32.dll的ReadFile映射为直接读取字节。。。

CType mType = new CType();
fixed(CType* p = &mType)
{
    User32.ReadFile(fileHandle, (byte*) p, Marshal.SizeOf(mType),0);
}

在.NET 3.5中与lambdas语句一起使用时,Func<>类型是绝对的。这些功能允许自定义功能,并且可以很好地帮助用户提供可自定义的对象,而无需对其进行子类化或求助于某些有限的系统,例如跟踪列出用户想要监视的按钮或键的变量。此外,它们可以像常规方法一样被调用,也可以像变量一样被赋值。我能想到的唯一缺点是,你只能有5个论点!尽管到那时你可能想考虑一个不同的解决方案。。。编辑:提供一些示例。

...
public Func<InputHelper, float> _horizontalCameraMovement = (InputHelper input) => 
{
    return (input.LeftStickPosition.X * _moveRate) * _zoom;
}
public Func<InputHelper, float> _verticalCameraMovement = (InputHelper input) => 
{
    return (-input.LeftStickPosition.Y * _moveRate) * _zoom;
}
...
public void Update(InputHelper input)
{
    ...
    position += new Vector2(_horizontalCameraMovement(input), _verticalCameraMovement(input));
    ...
}

在本例中,您可以编写一个函数,该函数执行任意计算并返回一个浮点值,该值将确定相机移动的量。这不是最好的代码,但它可以跨越这一点。

private int foo;
public int FooProperty {
    get
    {
        if (_onFooGotten() == true)
            return _foo;
    }
    set
    {
        if (onFooSet() == true)
            _foo = value;
    }
}
...
public Func<bool> _onFooGotten = () => 
{
    //do whatever...
    return true;
}
public Func<bool> _onFooSet = () =>
{
    //do whatever...
    return true;
}

这并不是最好的例子(因为我还没有真正探讨过这个用法),但它展示了一个使用lambda函数进行快速事件引发的例子,而没有代理的麻烦。编辑:想到了另一个。空值!C#最接近可选参数。

允许使用带大括号的空块。

你可以这样写代码

{
    service.DoTonsOfWork(args);
}

当你想尝试一些没有使用或尝试的东西时,这是很有帮助的。。。最后,你已经写好了。

//using(var scope = new TransactionScope)
{
    service.DoTonsOfWork(args);
}

很抱歉这么晚才发布,我是Stack Overflow的新手,因此错过了之前的机会。

我发现EventHandler<T>是该框架的一个很好的功能,但未得到充分利用。

我遇到的大多数C#开发人员在定义自定义事件时仍然会定义自定义事件处理程序委托,这不再是必要的。

而不是:

public delegate void MyCustomEventHandler(object sender, MyCustomEventArgs e);

public class MyCustomEventClass 
{
    public event MyCustomEventHandler MyCustomEvent;
}

你可以去:

public class MyCustomEventClass 
{
    public event EventHandler<MyCustomEventArgs> MyCustomEvent;
}

这要简洁得多,而且您不会陷入这样的两难境地:是将委托放在包含事件的类的.cs文件中,还是EventArgs派生类中。