xvd*_*iff 6 .net c# reflection inheritance il
因此,今天我使用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);
}
}
Run Code Online (Sandbox Code Playgroud)
据我所看到的,派生类不调用摆在首位的基础构造,而是做一些事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>)
Run Code Online (Sandbox Code Playgroud)
你可以这样做:
public class SomeDerivedClass : SomeBaseClass {
public SomeDerivedClass(SomeType onlyOneInstance)
: base(new[] { onlyOneInstance})
{
}
}
Run Code Online (Sandbox Code Playgroud)
换句话说,您绝对可以在基本构造函数之前运行代码,作为构造传递给它的参数的一部分。在本例中,我们正在构造一个数组以传递给基类。您还可以调用静态方法,如递归提到的那样。
我错过了空检查。显然他们想要保留 null 传递情况而不是包含 null 的数组。这相当于:
public class SomeDerivedClass : SomeBaseClass {
public SomeDerivedClass(SomeType onlyOneInstance)
: base(onlyOneInstance != null ? new [] { onlyOneInstance} : null)
{
}
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3004 次 |
| 最近记录: |