在我从这个问题中了解到以下内容后,我想到了这一点:
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的并行扩展
纯安全C中的联合(C++共享内存类型)#
在不使用不安全模式和指针的情况下,可以让类成员共享类/结构中的内存空间。给定以下类别:
[StructLayout(LayoutKind.Explicit)]
public class A
{
[FieldOffset(0)]
public byte One;
[FieldOffset(1)]
public byte Two;
[FieldOffset(2)]
public byte Three;
[FieldOffset(3)]
public byte Four;
[FieldOffset(0)]
public int Int32;
}
您可以通过操作Int32字段来修改字节字段的值,反之亦然。例如,该程序:
static void Main(string[] args)
{
A a = new A { Int32 = int.MaxValue };
Console.WriteLine(a.Int32);
Console.WriteLine("{0:X} {1:X} {2:X} {3:X}", a.One, a.Two, a.Three, a.Four);
a.Four = 0;
a.Three = 0;
Console.WriteLine(a.Int32);
}
输出以下内容:
2147483647
FF FF FF 7F
65535
只需添加使用System.Runtime.InteropServices;
其他一切,加上
1) 隐式泛型(为什么只在方法上而不在类上?)
void GenericMethod<T>( T input ) { ... }
//Infer type, so
GenericMethod<int>(23); //You don't need the <>.
GenericMethod(23); //Is enough.
2) 具有一个参数的简单lambdas:
x => x.ToString() //simplify so many calls
3) 匿名类型和初始化程序:
//Duck-typed: works with any .Add method.
var colours = new Dictionary<string, string> {
{ "red", "#ff0000" },
{ "green", "#00ff00" },
{ "blue", "#0000ff" }
};
int[] arrayOfInt = { 1, 2, 3, 4, 5 };
另一个:
4) 自动财产可以有不同的范围:
public int MyId { get; private set; }
感谢@pzycoman提醒我:
5) 命名空间别名(并非您可能需要这种特殊区分):
using web = System.Web.UI.WebControls;
using win = System.Windows.Forms;
web::Control aWebControl = new web::Control();
win::Control aFormControl = new win::Control();
与使用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));
更干净,更容易理解