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

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的并行扩展


当前回答

在lambda发挥作用之前,它是匿名委托。这可以用于与Ruby的blockgiven类似的总括代码。但我还没有测试lambda的工作原理,因为到目前为止我想坚持使用.NET2.0。

例如,当您希望确保记住关闭HTML标记时:

MyHtmlWriter writer=new MyHtmlWriter();
writer.writeTag("html", 
  delegate ()
  { 
    writer.writeTag("head", 
       delegate() 
       { 
           writer.writeTag("title"...);
       }
    )
  })

我确信,如果lambda是一个选项,那么会产生更干净的代码:)

其他回答

可以在非泛型类中使用泛型方法。

RealProxy允许您为现有类型创建自己的代理。

这是非常先进的,我没有见过其他人使用它——这可能意味着它对大多数人来说真的没有那么有用——但这是值得了解的事情之一。

基本上,.NET RealProxy类允许您创建另一种类型的透明代理。在这种情况下,透明意味着它看起来完全像客户端的代理目标对象——但实际上不是:它是从RealProxy派生的类的实例。

这使您可以在客户端和在实际目标对象上调用的任何方法或财产之间应用强大而全面的拦截和“中介”服务。将此功能与工厂模式(IoC等)结合起来,您可以将透明代理而不是真实对象交回,从而允许您拦截对真实对象的所有调用,并在每次方法调用前后执行操作。事实上,我相信这正是.NET用于跨应用程序域、进程和计算机边界远程处理的功能:.NET拦截所有访问,向远程对象发送序列化信息,接收响应,并将其返回到代码。

也许有一个例子可以说明这是如何有用的:我为我作为企业架构师的最后一份工作创建了一个参考服务堆栈,它指定了部门内任何新WCF服务的标准内部组合(“堆栈”)。该模型要求Foo服务的数据访问层实现IDAL<Foo>:创建Foo,读取Foo,更新Foo,删除Foo。服务开发人员使用(来自我的)提供的公共代码来定位和加载服务所需的DAL:

IDAL<T> GetDAL<T>(); // retrieve data access layer for entity T

该公司的数据访问策略常常受到性能挑战。作为一名架构师,我不能监督每一个服务开发人员,以确保他/她编写了一个高性能的数据访问层。但我在GetDAL工厂模式中可以做的是为请求的DAL创建一个透明的代理(一旦公共服务模型代码找到了DLL并加载了它),并使用高性能计时API来配置对DAL的任何方法的所有调用。然后,对落后者进行排名只是按照总时间降序排序DAL呼叫计时的问题。与开发评测(例如在IDE中)相比,这种评测的优势在于它也可以在生产环境中进行,以确保SLA。

下面是我为“实体分析器”编写的测试代码示例,这是用一行为任何类型创建分析代理的常见代码:

[Test, Category("ProfileEntity")]
public void MyTest()
{
    // this is the object that we want profiled.
    // we would normally pass this around and call
    // methods on this instance.
    DALToBeProfiled dal = new DALToBeProfiled();

    // To profile, instead we obtain our proxy
    // and pass it around instead.
    DALToBeProfiled dalProxy = (DALToBeProfiled)EntityProfiler.Instance(dal);

    // or...
    DALToBeProfiled dalProxy2 = EntityProfiler<DALToBeProfiled>.Instance(dal);

    // Now use proxy wherever we would have used the original...
    // All methods' timings are automatically recorded
    // with a high-resolution timer
    DoStuffToThisObject(dalProxy);

    // Output profiling results
    ProfileManager.Instance.ToConsole();
}

同样,这让您可以截获客户端对目标对象调用的所有方法和财产!在RealProxy派生类中,必须重写Invoke:

[System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Never)]
[SecurityPermission(SecurityAction.LinkDemand, 
    Flags = SecurityPermissionFlag.Infrastructure)] // per FxCop
public override IMessage Invoke(IMessage msg)
{
    IMethodCallMessage msgMethodCall = msg as IMethodCallMessage;
    Debug.Assert(msgMethodCall != null); // should not be null - research Invoke if this trips. KWB 2009.05.28

    // The MethodCallMessageWrapper
    // provides read/write access to the method 
    // call arguments. 
    MethodCallMessageWrapper mc =
        new MethodCallMessageWrapper(msgMethodCall);

    // This is the reflected method base of the called method. 
    MethodInfo mi = (MethodInfo)mc.MethodBase;

    IMessage retval = null;

    // Pass the call to the method and get our return value
    string profileName = ProfileClassName + "." + mi.Name;

    using (ProfileManager.Start(profileName))
    {
        IMessage myReturnMessage =
           RemotingServices.ExecuteMessage(_target, msgMethodCall);

        retval = myReturnMessage;
    }

    return retval;
}

.NET的功能是不是很迷人?唯一的限制是目标类型必须从MarshalByRefObject派生。我希望这对某人有帮助。

使用Delegate.CreateDelegate调用私有方法的技巧非常简单。

var subject = new Subject();
var doSomething = (Func<String, String>)
    Delegate.CreateDelegate(typeof(Func<String, String>), subject, "DoSomething");
Console.WriteLine(doSomething("Hello Freggles"));

这是一个有用的上下文

类型定义

有人发帖说他们错过了typedef,但你可以这样做

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

并声明为

ListOfDictionary list = new ListOfDictionary();

关于事件处理程序的另一个注意事项:您可以简单地创建一个raise扩展方法,如下所示:

public static class EventExtensions {
    public static void Raise<T>(this EventHandler<T> @event, 
                                object sender, T args) where T : EventArgs {
        if(@event!= null) {
            @event(sender, args);
        }
    }
}

然后可以使用它引发事件:

public class MyImportantThing {
    public event EventHandler<MyImportantEventEventArgs> SomethingHappens;
    ...
    public void Bleh() {
        SomethingHappens.Raise(this, new MyImportantEventEventArgs { X=true });
    }
}

此方法的另一个优点是强制执行编码标准(使用EventHandler<>)。

一次又一次地编写相同的精确函数是没有意义的。也许下一个版本的C#最终会有一个InlineAttribute,它可以放在扩展方法上,并使编译器内联方法定义(这将使这种方式接近标准,而且速度最快)。

编辑:基于注释删除扩展方法中的临时变量