【.NET】利用 IL 魔法实现随心随意的泛型约束
众所周知,C# 只支持对 基类/接口/class/struct/new() 以及一些 IDE 魔法的约束,比如这样 public static string Test < T >( T value ) where T : ITest { return value .Test(); } public interface ITest { string Test () ; } 但是如果我们想要随心所欲的约束就不行了 public static string Test < T >( T value ) where T : { string Test () ; } { return value .Test(); } 最近无聊乱折腾 MSIL,弄出来好多不能跑的魔法,虽然不能跑但是反编译出的 C# 看着很神奇,其中正好就有想看看能不能弄个神奇的泛型出来,于是我胡写了一段代码 .assembly _ { } .class public Test { .method public void .ctor () { ldarg.0 call instance void object :: .ctor () ret } .method public static void Main () { .entrypoint newobj instance void Test :: .ctor () call string Test :: Test < class Test >(!! 0 ) call void [ mscorlib ] System.Console :: WriteLine ( string ) ret } .method public static string Test < T >(!! T t ) { ldarg.s t callvirt inst...