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

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


当前回答

直到我将Convert类中的一些函数与Array.ConvertAll组合在一起,我才弄清楚它们的用途(例如Convert.ToDouble(int)、Convert.ToInt(double)):

int[] someArrayYouHaveAsInt;
double[] copyOfArrayAsDouble = Array.ConvertAll<int, double>(
                                someArrayYouHaveAsInt,
                                new Converter<int,double>(Convert.ToDouble));

这避免了由于定义内联委托/闭包而产生的资源分配问题(并且稍微更易读):

int[] someArrayYouHaveAsInt;
double[] copyOfArrayAsDouble = Array.ConvertAll<int, double>(
                                someArrayYouHaveAsInt,
                                new Converter<int,double>(
                                  delegate(int i) { return (double)i; }
                                ));

其他回答

也许这不是一种先进的技术,但我一直看到一种让我疯狂的技术:

if (x == 1)
{
   x = 2;
}
else
{
   x = 3;
}

可以浓缩成:

x = (x==1) ? 2 : 3;

IOobservable怎么样?

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

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

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

我经常遇到需要将泛型参数对象持久化为基类中的视图状态。

public abstract class BaseListControl<ListType,KeyType,ParameterType>
                 : UserControl 
                 where ListType : BaseListType
                 && ParameterType : BaseParameterType, new
{

    private const string viewStateFilterKey = "FilterKey";

    protected ParameterType Filters
    {
        get
        {
            if (ViewState[viewStateFilterKey] == null)
                ViewState[viewStateFilterKey]= new ParameterType();

            return ViewState[viewStateFilterKey] as ParameterType;
        }
        set
        {
            ViewState[viewStateFilterKey] = value;
        }
    }

}

用法:

private void SomeEventHappened(object sender, EventArgs e)
{
    Filters.SomeValue = SomeControl.SelectedValue;
}

private void TimeToFetchSomeData()
{
    GridView.DataSource = Repository.GetList(Filters);
}

“where ParameterType:BaseParameterType,new”的这个小技巧使它真正起作用。

在我的基类中有了这个属性,我可以自动处理分页,设置过滤器值以过滤网格视图,使排序变得非常容易,等等。

我真的只是想说,在错误的手中,仿制药可能是一种非常强大的野兽。

C#允许您将属性setter方法添加到实现只读接口财产的具体类型中,即使接口声明本身没有属性setter。例如:

public interface IReadOnlyFoo
{
   object SomeReadOnlyProperty { get; }
}

具体类如下所示:

internal class Foo : IReadOnlyFoo
{
   public object SomeReadOnlyProperty { get; internal set; }
}

有趣的是,如果将Foo类强制转换为IReadOnlyFoo接口,则它是不可变的:

// Create a Foo instance
Foo foo = new Foo();

// This statement is legal
foo.SomeReadOnlyProperty = 12345;

// Make Foo read only
IReadOnlyFoo readOnlyFoo = foo;

// This statement won't compile
readOnlyFoo.SomeReadOnlyProperty = 54321;

除了duncansmart的回复,还可以在Framework 2.0上使用扩展方法。只需在System.Runtime.CompilerServices命名空间下添加一个ExtensionAttribute类,就可以使用扩展方法(当然,仅适用于C#3.0)。

namespace System.Runtime.CompilerServices
{
    public class ExtensionAttribute : Attribute
    { 
    }
}