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

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

其他回答

我很长一段时间都不知道“as”关键字。

MyClass myObject = (MyClass) obj;

vs

MyClass myObject = obj as MyClass;

如果obj不是MyClass,则第二个将返回null,而不是引发类强制转换异常。

我倾向于发现大多数C#开发人员不知道“可空”类型。基本上,基元可以具有空值。

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

将一个可为null的双精度值num1设置为null,然后将一个常规双精度值num 2设置为num1或-100(如果num1为null)。

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

关于Nullable类型还有一点:

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

它是返回String.Empty。有关详细信息,请查看此链接

你可以打开字符串!

switch(name)
{
  case "Dave":
    return true;
  case "Bob":
    return false;
  default:
    throw new ApplicationException();
}

非常方便!比一堆if else语句更干净

我想说,将某些系统类用于扩展方法非常方便,例如system.Enum,您可以执行以下操作。。。

[Flags]
public enum ErrorTypes : int {
    None = 0,
    MissingPassword = 1,
    MissingUsername = 2,
    PasswordIncorrect = 4
}

public static class EnumExtensions {

    public static T Append<T> (this System.Enum type, T value) where T : struct
    {
        return (T)(ValueType)(((int)(ValueType) type | (int)(ValueType) value));
    }

    public static T Remove<T> (this System.Enum type, T value) where T : struct
    {
        return (T)(ValueType)(((int)(ValueType)type & ~(int)(ValueType)value));
    }

    public static bool Has<T> (this System.Enum type, T value) where T : struct
    {
        return (((int)(ValueType)type & (int)(ValueType)value) == (int)(ValueType)value);
    }

}

...

//used like the following...

ErrorTypes error = ErrorTypes.None;
error = error.Append(ErrorTypes.MissingUsername);
error = error.Append(ErrorTypes.MissingPassword);
error = error.Remove(ErrorTypes.MissingUsername);

//then you can check using other methods
if (error.Has(ErrorTypes.MissingUsername)) {
    ...
}

当然,这只是一个例子——这些方法可能需要更多的工作。。。

与使用int.TryParse()或Convert.ToInt32()不同,我喜欢有一个静态整数解析函数,当它无法解析时返回null。那么我可以使用??和三元运算符一起使用,以更清楚地确保我的声明和初始化都在一行中以易于理解的方式完成。

public static class Parser {
    public static int? ParseInt(string s) {
        int result;
        bool parsed = int.TryParse(s, out result);
        if (parsed) return result;
        else return null;
    }
    // ...
}

这对于避免重复赋值的左侧也是很好的,但对于避免在赋值的右侧重复长调用(例如下面的示例中的数据库调用)则更好。而不是丑陋的“如果那么”树(我经常遇到):

int x = 0;
YourDatabaseResultSet data = new YourDatabaseResultSet();
if (cond1)
    if (int.TryParse(x_input, x)){
        data = YourDatabaseAccessMethod("my_proc_name", 2, x);
    }
    else{
        x = -1;
        // do something to report "Can't Parse"    
    }
}
else {
    x = y;
    data = YourDatabaseAccessMethod("my_proc_name", 
       new SqlParameter("@param1", 2),
       new SqlParameter("@param2", x));
}

您可以执行以下操作:

int x = cond1 ? (Parser.ParseInt(x_input) ?? -1) : y;
if (x >= 0)  data = YourDatabaseAccessMethod("my_proc_name", 
    new SqlParameter("@param1", 2),
    new SqlParameter("@param2", x));

更干净,更容易理解