C#的隐藏特性?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/9033/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-07-31 17:23:15  来源:igfitidea点击:

Hidden Features of C#?

提问by Serhat Ozgel

This came to my mind after I learned the following from this question:

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

where T : struct

We, C# developers, all know the basics of C#. I mean declarations, conditionals, loops, operators, etc.

我们,C# 开发人员,都知道 C# 的基础知识。我的意思是声明、条件、循环、运算符等。

Some of us even mastered the stuff like Generics, anonymous types, lambdas, LINQ, ...

我们中的一些人甚至掌握了泛型匿名类型lambdasLINQ等东西。

But what are the most hidden features or tricks of C# that even C# fans, addicts, experts barely know?

但是,即使是 C# 爱好者、瘾君子、专家也几乎不知道的 C# 最隐藏的特性或技巧是什么?

Here are the revealed features so far:

以下是迄今为止已揭示的功能:



Keywords

关键词

Attributes

属性

Syntax

句法

Language Features

语言特点

Visual Studio Features

Visual Studio 功能

Framework

框架

Methods and Properties

方法和属性

Tips & Tricks

提示与技巧

  • Nice method for event handlers by Andreas H.R. Nilsson
  • Uppercase comparisons by John
  • Access anonymous types without reflection by dp
  • A quick way to lazily instantiate collection properties by Will
  • JavaScript-like anonymous inline-functions by roosteronacid

Other

其他

回答by Michael Stum

"yield" would come to my mind. Some of the attributes like [DefaultValue()]are also among my favorites.

屈服”会出现在我的脑海中。[DefaultValue()]等一些属性也是我的最爱。

The "var" keyword is a bit more known, but that you can use it in .NET 2.0 applications as well (as long as you use the .NET 3.5 compilerand set it to output 2.0 code) does not seem to be known very well.

var”关键字更为人所知,但您也可以在 .NET 2.0 应用程序中使用它(只要您使用 .NET 3.5 编译器并将其设置为输出 2.0 代码)似乎不太为人所知好。

Edit: kokos, thanks for pointing out the ?? operator, that's indeed really useful. Since it's a bit hard to google for it (as ?? is just ignored), here is the MSDN documentation page for that operator: ?? Operator (C# Reference)

编辑:kokos,感谢您指出 ?? 运营商,这确实非常有用。由于谷歌搜索有点困难(因为 ?? 只是被忽略了),这里是该运营商的 MSDN 文档页面:?? 运算符(C# 参考)

回答by kokos

  1. ??- coalescing operator
  2. using (statement/ directive) - great keyword that can be used for more than just calling Dispose
  3. readonly- should be used more
  4. netmodules - too bad there's no support in Visual Studio
  1. ?? - 合并运算符
  2. using ( statement/ directive) - 伟大的关键字,不仅可以用于调用 Dispose
  3. readonly- 应该更多地使用
  4. netmodules - 太糟糕了,Visual Studio 不支持

回答by TheSmurf

Two of my personal favourites, which I see rarely used:

我个人最喜欢的两个,我很少使用:

  1. Snippets (particularly for properties, which was made even better for Visual Studio 2008)
  2. The ObsoleteAttribute
  1. 片段(尤其是属性,它在 Visual Studio 2008 中做得更好)
  2. ObsoleteAttribute

回答by Nick Berardi

Honestly the experts by the very definition should know this stuff. But to answer your question: Built-In Types Table (C# Reference)

老实说,按照定义的专家应该知道这些东西。但是要回答您的问题:内置类型表(C# 参考)

The compiler flagging for numbers are widely known for these:

数字的编译器标记因以下原因而广为人知:

Decimal = M
Float = F
Double = D

// for example
double d = 30D;

However these are more obscure:

然而,这些更模糊:

Long = L
Unsigned Long = UL
Unsigned Int = U

回答by Mike Stone

I didn't know the "as" keyword for quite a while.

我有一段时间不知道“as”关键字。

MyClass myObject = (MyClass) obj;

vs

对比

MyClass myObject = obj as MyClass;

The second will return null if obj isn't a MyClass, rather than throw a class cast exception.

如果 obj 不是 MyClass,则第二个将返回 null,而不是抛出类转换异常。

回答by JamesSugrue

  • TransactionScope and DependentTransactionin System.Transactions is a lightweight way to use transaction processing in .NET - it's not just for Database transactions either
  • String.IsNullOrEmpty is one that I am surprised to learn a lot of developers don't know about
  • List.ForEach - iterate through your generic list using a delegate method
  • System.Transactions 中的TransactionScope 和DependentTransaction是一种在 .NET 中使用事务处理的轻量级方法 - 它不仅适用于数据库事务
  • String.IsNullOrEmpty 是我惊讶地发现很多开发人员不知道的
  • List.ForEach - 使用委托方法遍历通用列表

There are more, but that is the three obvious ones of the top of my head...

还有更多,但这是我头顶最明显的三个......

回答by Stu

Attributes in general, but most of all DebuggerDisplay. Saves you years.

属性一般,但最重要的是DebuggerDisplay。为您节省数年。

回答by Brad Barker

I tend to find that most C# developers don't know about 'nullable' types. Basically, primitives that can have a null value.

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

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

Set a nullable double, num1, to null, then set a regular double, num2, to num1or -100if num1was null.

将可空双精度 num1设置为空,然后将常规双精度 num2设置为num1-100(如果num1为空)。

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

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

one more thing about Nullable type:

关于 Nullable 类型的另一件事:

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

it is return String.Empty. Check thislink for more details

它是返回 String.Empty。查看链接了解更多详情

回答by Lars M?hlum

I have often come across the need to have a generic parameter-object persisted into the viewstate in a base class.

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

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;
        }
    }

}

Usage:

用法:

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

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

This little trick with the "where ParameterType : BaseParameterType, new" is what makes it really work.

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

With this property in my baseclass, I can automate handling of paging, setting filter values to filter a gridview, make sorting really easy, etc.

使用我的基类中的这个属性,我可以自动处理分页、设置过滤器值来过滤 gridview、使排序变得非常容易等。

I am really just saying that generics can be an enormously powerful beast in the wrong hands.

我真的只是说泛型在坏人手中可能是一个非常强大的野兽。

回答by Dogmang

@Ed, I'm a bit reticent about posting this as it's little more than nitpicking. However, I would point out that in your code sample:

@Ed,我对发布此内容持谨慎态度,因为它只不过是吹毛求疵。但是,我会在您的代码示例中指出:

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

If you're going to use 'is', why follow it up with a safe cast using 'as'? If you've ascertained that obj is indeed MyClass, a bog-standard cast:

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

c = (MyClass)obj

...is never going to fail.

......永远不会失败。

Similarly, you could just say:

同样,你可以说:

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

I don't know enough about .NET's innards to be sure, but my instincts tell me that this would cut a maximum of two type casts operations down to a maximum of one. It's hardly likely to break the processing bank either way; personally, I think the latter form looks cleaner too.

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