因此,今天我使用ILSpy dotPeek反映了一个使用ILSpy dotPeek的仲裁.NET程序集,以便在我偶然发现这个奇怪的部分(虚拟示例)时更深入地了解IL代码的工作原理:
public class SomeBaseClass { public SomeBaseClass(SomeType[] iExpectACollection) { ... } } public class SomeDerivedClass { public SomeDerivedClass(SomeType onlyOneInstance) { SomeType[] collection; if(onlyOneInstance != null) collection = new SomeType[] { onlyOneInstance }; base.\u002Ector(collection); } }
据我所知,派生类首先不调用基本构造函数,而是使用onlyOneInstance执行某些操作,然后调用基本构造函数.
我的问题是:在完成一些工作后,是否可以在C#中显式调用基础构造函数?或者这只能在IL中使用?我知道它很容易在例如Java使用super(),但我从未在.NET中看到它.
编辑
我刚和老板谈过,他可以发布一些真实的图书馆代码(这是我们公司的内部代码之一):
**IL PART** .method public hidebysig specialname rtspecialname instance void .ctor ( string contextId,class MyComp.NetStack.BufferManager bufferManager,class MyComp.NetStack.TcpChannelQuotas quotas,class [System]System.Security.Cryptography.X509Certificates.X509Certificate2 clientCertificate,class [System]System.Security.Cryptography.X509Certificates.X509Certificate2[] clientCertificateChain,class [System]System.Security.Cryptography.X509Certificates.X509Certificate2 serverCertificate,class MyComp.NetStack.EndpointDescription endpoint,class MyComp.NetStack.ApplicationThreadPool threadPool ) cil managed { // Method begins at RVA 0x648e0 // Code size 263 (0x107) .maxstack 10 .locals init ( [0] class MyComp.NetStack.EndpointDescription[] ) IL_0000: ldarg.0 IL_0001: ldarg.1 IL_0002: ldarg.2 IL_0003: ldarg.3 IL_0004: ldarg.s serverCertificate IL_0006: ldarg.s clientCertificateChain IL_0008: ldarg.s endpoint IL_000a: brtrue.s IL_000f IL_000c: ldnull IL_000d: br.s IL_0021 IL_000f: ldc.i4.1 IL_0010: newarr MyComp.NetStack.EndpointDescription IL_0015: stloc.0 IL_0016: ldloc.0 IL_0017: ldc.i4.0 IL_0018: ldarg.s endpoint IL_001a: stelem.ref IL_001b: ldloc.0 IL_001c: newobj instance void MyComp.NetStack.EndpointDescriptionCollection::.ctor(class [mscorlib]System.Collections.Generic.IEnumerable`1<class MyComp.NetStack.EndpointDescription>)
解决方法
你可以这样做:
public class SomeDerivedClass : SomeBaseClass { public SomeDerivedClass(SomeType onlyOneInstance) : base(new[] { onlyOneInstance}) { } }
换句话说,您肯定可以在基础构造函数之前运行代码,作为构造传递给它的参数的一部分.在这种情况下,我们正在构造一个数组以传递给基类.您还可以调用静态方法,如递归提及.
我错过了空检查.显然,他们希望保留null传递大小写而不是包含null的数组.这相当于:
public class SomeDerivedClass : SomeBaseClass { public SomeDerivedClass(SomeType onlyOneInstance) : base(onlyOneInstance != null ? new [] { onlyOneInstance} : null) { } }