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

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


当前回答

HttpContext.Current.Server.Execute 

非常适合将HTML呈现为AJAX回调的字符串。您可以将其与组件一起使用,而不是将HTML字符串片段拼接在一起。我能够在几乎没有混乱的情况下将页面膨胀减少几百KB。我是这样使用的:

Page pageHolder = new Page();
UserControl viewControl = (UserControl)pageHolder.LoadControl(@"MyComponent.ascx");
pageHolder.Controls.Add(viewControl);
StringWriter output = new StringWriter();
HttpContext.Current.Server.Execute(pageHolder, output, false);
return output.ToString();

其他回答

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派生。我希望这对某人有帮助。

InternalsVisibleTo属性是一个不太为人所知的属性,但在某些情况下,它会变得越来越有用。它基本上允许另一个程序集访问定义程序集的“内部”元素。

首先-DebuggerTypeProxy。

[DebuggerTypeProxy(typeof(HashtableDebugView))]
class MyHashtable : Hashtable
{
    private const string TestString = 
        "This should not appear in the debug window.";

    internal class HashtableDebugView
    {
        private Hashtable hashtable;
        public const string TestStringProxy = 
            "This should appear in the debug window.";

        // The constructor for the type proxy class must have a 
        // constructor that takes the target type as a parameter.
        public HashtableDebugView(Hashtable hashtable)
        {
            this.hashtable = hashtable;
        }
    }
}

第二步:

ICustomTypeDescriptor

框架功能

我不知道,但我对VisualStyleRenderer和整个System.Windows.Forms.VisualStyles-Namespace感到非常惊讶。非常酷!

我喜欢这样一个事实:我可以在普通的旧.NET 2.0上使用LINQ对象(即不需要到处安装.NET 3.5)。您只需要实现所有查询运算符Extension方法-请参阅LINQBridge