我是一个绝对的初学者,你看。说我有堆栈上的字符串对象,并希望得到它的字符数 - 它。长度属性。我怎么会得到隐藏在里面的INT32多少?

提前感谢!

有帮助吗?

解决方案

有真的没有这样的事情在IL特性。只有字段和方法。 C#的属性结构转换为get_PropertyName和编译器set_PropertyName方法,所以你要调用这些方法来访问属性。

样品(调试)IL代码

var s = "hello world";
var i = s.Length;

IL

  .locals init ([0] string s,
           [1] int32 i)
  IL_0000:  nop
  IL_0001:  ldstr      "hello world"
  IL_0006:  stloc.0
  IL_0007:  ldloc.0
  IL_0008:  callvirt   instance int32 [mscorlib]System.String::get_Length()
  IL_000d:  stloc.1

正如你可以看到Length属性经由呼叫get_Length访问。

其他提示

我被骗了......我把下面的C#代码和反汇编器/反射

看了看它
static void Main(string[] args)
{
    string h = "hello world";
    int i = h.Length;
}

等同于

.method private hidebysig static void Main(string[] args) cil managed
{
    .entrypoint
    .maxstack 1
    .locals init (
        [0] string h,
        [1] int32 i)
    L_0000: nop 
    L_0001: ldstr "hello world"
    L_0006: stloc.0 
    L_0007: ldloc.0 
    L_0008: callvirt instance int32 [mscorlib]System.String::get_Length()
    L_000d: stloc.1 
    L_000e: ret 
}
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top