你見過哪些令你瞠目結舌的C#代碼?
人民幣金額大寫轉換
忘了從哪抄的了……當時看到後整個人都軼可賽艇了
public static String ConvertToChinese(Decimal number)
{
var s = number.ToString("#L#E#D#C#K#E#D#C#J#E#D#C#I#E#D#C#H#E#D#C#G#E#D#C#F#E#D#C#.0B0A");
var d = Regex.Replace(s, @"((?&<=-|^)[^1-9]*)|((?"z"0)[0A-E]*((?=[1-9])|(?"-z"(?=[F-L.]|$))))|((?"b"[F-L])(?"z"0)[0A-L]*((?=[1-9])|(?"-z"(?=[.]|$))))", "${b}${z}");
var r = Regex.Replace(d, ".", m =&> "負元空零壹貳叄肆伍陸柒捌玖空空空空空空空分角拾佰仟萬億兆京垓秭穰"[m.Value[0] - "-"].ToString());
if (r.EndsWith("元"))//這兩行是我加的
r += "整";//感覺我拉低了前邊代碼的逼格……很慚愧
return r;
}
對著這三行他認識我我不認識他的代碼看了半天,然並卵,so sad,對正則一知半解的我只能膜一下了……
如果有大神來認領請直接回復……Monadic Parser Combinators using C# 3.0
這篇文章讓我當年對C#有了無限的好感,直到現在又到讓這篇老文出場的時候了:要讓CLR掛掉的話(第二彈)……
(印象中以前在知乎的別的啥問題里用過此文了…但想不起是啥問題了orz對了俺還寫過這些:- LINQ與DLR的Expression tree(5):用lambda表達式表示常見控制結構 &<- @vczh 提到的那篇monadic parser combinator博文給了我靈感…
- LINQ的惡搞……
- Visual Studio 2008的黑色主題,Dark Theme + Consolas字體 &<- 文中最後一張截圖裡的代碼有我寫的若干擴展方法
這個 Linq 和 Monad 呀,excited.Monads, part one
http://mikehadlow.blogspot.com/2011/01/monads-in-c-4-linq-loves-monads.html
//
using System;
using System.Reflection;
using System.Reflection.Emit;
public class Test1
{
delegate void HelloDelegate(Murong murong);
public static void Main(string[] args)
{
Murong murong = null;//注意murong是null哦~
Type[] helloArgs = {typeof(Murong)};
var hello = new DynamicMethod("Hello",
typeof(void), helloArgs,
typeof(Murong).Module);
ILGenerator il = hello.GetILGenerator(256);
il.Emit(OpCodes.Ldarg_0);
var foo = typeof(Murong).GetMethod("Foo");
il.Emit(OpCodes.Call, foo);
il.Emit(OpCodes.Ret);
var print = (HelloDelegate)hello.CreateDelegate(typeof(HelloDelegate));
print(murong);
}
internal class Murong
{
//注意Foo不是靜態方法額~
public void Foo()
{
Console.WriteLine("this == null is " + (this == null));
}
}
}

FormatterServices.GetUninitializedObject(type)
這方法好屌!
var result = delegate1()()()()()()()()()()()()()()()()()();
@RednaxelaFX 看到 from x in default(int) select x + 1 我震驚了。好吧。原來是自己實現的擴展方法。那我也來一個
class A : IEnumerable
{
public void Add(string s)
{
Console.WriteLine(s);
}
public IEnumerator GetEnumerator()
{
throw new NotImplementedException();
}
}
class Program
{
static void Main(string[] args)
{
A a = new A() { "張三", "李四" };
}
}

void Main()
{
object someObj = null;
Console.WriteLine(someObj.IsOK()); // show False;
}
第一次看到的時候稍微震驚了下,後面就想通了。
using System.Runtime.InteropServices;
namespace ConsoleApplication49
{
class Program
{
[DllImport("ntdll.dll")]
public static extern void RtlSetProcessIsCritical(int i, int j, int k);
static void Main(string[] args)
{
RtlSetProcessIsCritical(1, 0, 0);
}
}
}
歪個樓,在遠古的07 08年諸多同學糾結於如何繁體簡體漢字轉化的時候,我偶然發現VB .NET 有一個內嵌的API自動實現了這個功能…回頭我找找…

我一直以來偷懶的代碼,被同事瞠目結舌aa

推薦閱讀:
※有哪些令人拍案叫絕的代碼/優化?
※Mathematica怎樣才能提高可讀性?
※為什麼程序語言要設計成使用這麼多shift?
※為什麼說 Smalltalk 超前了 20 年?
※Mathematica 這門語言怎麼樣?
