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
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, ...
我们中的一些人甚至掌握了泛型、匿名类型、lambdas、LINQ等东西。
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
关键词
yield
by Michael Stumvar
by Michael Stumusing()
statement by kokosreadonly
by kokosas
by Mike Stoneas
/is
by Ed Swangrenas
/is
(improved) by Rocketpantsdefault
by deathofratsglobal::
by pzycomanusing()
blocks by AlexCusevolatile
by Jakub ?turcextern alias
by Jakub ?turc
yield
由迈克尔·葡萄汁var
由迈克尔·葡萄汁using()
科科斯的声明readonly
由kokosas
由迈克·斯通as
/is
由埃德Swangrenas
/is
(改进)由Rocketpantsdefault
通过deathofratsglobal::
由pzycommanusing()
由块AlexCusevolatile
作者:Jakub?turcextern alias
作者:Jakub?turc
Attributes
属性
DefaultValueAttribute
by Michael StumObsoleteAttribute
by DannySmurfDebuggerDisplayAttribute
by StuDebuggerBrowsable
andDebuggerStepThrough
by bdukesThreadStaticAttribute
by marxidadFlagsAttribute
by Martin ClarkeConditionalAttribute
by AndrewBurns
DefaultValueAttribute
由迈克尔·葡萄汁ObsoleteAttribute
通过DannySmurfDebuggerDisplayAttribute
由StuDebuggerBrowsable
并DebuggerStepThrough
通过bdukesThreadStaticAttribute
by marxidadFlagsAttribute
通过马丁克拉克ConditionalAttribute
作者:安德鲁伯恩斯
Syntax
句法
??
(coalesce nulls) operator by kokos- Number flaggings by Nick Berardi
where T:new
by Lars M?hlum- Implicit generics by Keith
- One-parameter lambdas by Keith
- Auto properties by Keith
- Namespace aliases by Keith
- Verbatim string literals with @ by Patrick
enum
values by lfoust- @variablenames by marxidad
event
operators by marxidad- Format string brackets by Portman
- Property accessor accessibility modifiers by xanadont
- Conditional (ternary) operator (
?:
) by JasonS checked
andunchecked
operators by Binoj Antonyimplicit and explicit
operators by Flory
??
(coalesce nulls) 操作符由kokos- Nick Berardi 的号码标记
where T:new
作者:拉斯·穆赫拉姆- Keith 的隐式泛型
- Keith 的单参数 lambda
- 基思的汽车属性
- Keith 的命名空间别名
- 带有 @ 的逐字字符串文字 by Patrick
enum
通过数值lfoust- @variablenames by marxidad
event
marxidad 的运营商- 波特曼格式化字符串括号
- xanadont 的属性访问器可访问性修饰符
- JasonS 的条件(三元)运算符 (
?:
) checked
和unchecked
运营商Binoj Antonyimplicit and explicit
Flory 的运营商
Language Features
语言特点
- Nullable types by Brad Barker
- Anonymous types by Keith
__makeref __reftype __refvalue
by Judah Himango- Object initializers by lomaxx
- Format strings by David in Dakota
- Extension Methods by marxidad
partial
methods by Jon Erickson- Preprocessor directives by John Asbeck
DEBUG
pre-processor directive by Robert Durgin- Operator overloading by SefBkn
- Type inferrence by chakrit
- Boolean operators taken to next levelby Rob Gough
- Pass value-type variable as interface without boxing by Roman Boiko
- Programmatically determine declared variable type by Roman Boiko
- Static Constructors by Chris
- Easier-on-the-eyes / condensed ORM-mapping using LINQ by roosteronacid
__arglist
by Zac Bowling
- Brad Barker 的可空类型
- Keith 的匿名类型
__makeref __reftype __refvalue
作者:犹大·希曼戈- lomaxx 的对象初始值设定项
- David 在达科他州的格式化字符串
- marxidad 的扩展方法
partial
乔恩·埃里克森的方法- John Asbeck 的预处理器指令
DEBUG
Robert Durgin 的预处理器指令- SefBkn 的运算符重载
- 通过chakrit 进行类型推断
- 布尔运算符带到一个新的水平由罗布·高夫
- Roman Boiko 将值类型变量作为接口传递,无需装箱
- 由Roman Boiko以编程方式确定声明的变量类型
- Chris 的静态构造函数
- 使用roosteronacid 的LINQ 更容易上眼/浓缩 ORM 映射
__arglist
通过扎克保龄球
Visual Studio Features
Visual Studio 功能
- Select block of text in editor by Himadri
- Snippets by DannySmurf
- Himadri在编辑器中选择文本块
- 通过片段DannySmurf
Framework
框架
TransactionScope
by KiwiBastardDependantTransaction
by KiwiBastardNullable<T>
by IainMHMutex
by DiagoSystem.IO.Path
by ageektrappedWeakReference
by Juan Manuel
TransactionScope
作者:KiwiBastardDependantTransaction
作者:KiwiBastardNullable<T>
作者:IainMHMutex
作者:迪亚哥System.IO.Path
受年龄限制WeakReference
通过胡安·曼努埃尔
Methods and Properties
方法和属性
String.IsNullOrEmpty()
method by KiwiBastardList.ForEach()
method by KiwiBastardBeginInvoke()
,EndInvoke()
methods by Will DeanNullable<T>.HasValue
andNullable<T>.Value
properties by RismoGetValueOrDefault
method by John Sheehan
String.IsNullOrEmpty()
KiwiBastard 的方法List.ForEach()
KiwiBastard 的方法BeginInvoke()
, Will Dean 的EndInvoke()
方法Nullable<T>.HasValue
并Nullable<T>.Value
通过性能RismoGetValueOrDefault
John Sheehan 的方法
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
- Andreas HR Nilsson 的事件处理程序的好方法
- John 的大写比较
- 访问匿名类型而无需通过dp进行反射
- 一种通过Will延迟实例化集合属性的快速方法
- roosteronacid的类似 JavaScript 的匿名内联函数
Other
其他
- netmodules by kokos
- LINQBridgeby Duncan Smart
- Parallel Extensionsby Joel Coehoorn
- kokos 的网络模块
- LINQBridge由邓肯智能
- 并行扩展由乔尔Coehoorn
回答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
回答by TheSmurf
Two of my personal favourites, which I see rarely used:
我个人最喜欢的两个,我很少使用:
- Snippets (particularly for properties, which was made even better for Visual Studio 2008)
- The ObsoleteAttribute
- 片段(尤其是属性,它在 Visual Studio 2008 中做得更好)
- 该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 的内部结构,但我的直觉告诉我,这会将最多两种类型转换操作减少到最多一种。无论哪种方式,都不太可能破坏处理库;就个人而言,我认为后一种形式看起来也更干净。