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

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


当前回答

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

其他回答

@艾德,我有点不愿意发表这篇文章,因为这只是吹毛求疵。但是,我要指出,在您的代码示例中:

MyClass c;
  if (obj is MyClass)
    c = obj as MyClass

如果你要使用“is”,为什么要使用“as”进行安全的转换?如果你确定obj确实是MyClass,一个泥沼标准演员:

c = (MyClass)obj

…永远不会失败。

同样,你可以说:

MyClass c = obj as MyClass;
if(c != null)
{
   ...
}

我对.NET的内部结构了解不多,但我的直觉告诉我,这会将最多两个类型转换操作减少到最多一个。无论哪种方式都不太可能打破处理银行;我个人认为,后一种形式看起来也更干净。

看到上面提到List.ForEach;2.0引入了一系列基于谓词的集合操作-Find、FindAll、Exists等。加上匿名委托,您几乎可以实现3.5的lambda表达式的简单性。

不是C#的具体内容,但我是一个三元操作迷。

而不是

if (boolean Condition)
{
    //Do Function
}
else
{
    //Do something else
}

你可以用一个简洁的

booleanCondtion ? true operation : false operation;

e.g.

而不是

int value = param;
if (doubleValue)
{
    value *= 2;
}
else
{
    value *= 3;
}

您可以键入

int value = param * (tripleValue ? 3 : 2);

它确实有助于编写简洁的代码,但嵌套这些该死的东西可能会令人讨厌,它们可能会被用于邪恶,但我还是喜欢那些小笨蛋

固定/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);
}

完全访问调用堆栈:

public static void Main()
{
  StackTrace stackTrace = new StackTrace();           // get call stack
  StackFrame[] stackFrames = stackTrace.GetFrames();  // get method calls (frames)

  // write call stack method names
  foreach (StackFrame stackFrame in stackFrames)
  {
    Console.WriteLine(stackFrame.GetMethod().Name);   // write method name
  }
}

所以,如果你选择第一个-你知道你在哪个函数中。如果你正在创建一个助手跟踪函数-在最后一个之前选择一个-你就会知道你的调用者。