gpt4 book ai didi

c# - 使属性与 CLR 一起工作的魔力是什么?

转载 作者:太空狗 更新时间:2023-10-29 18:18:47 24 4
gpt4 key购买 nike

我注意到当我反射(reflect)到程序集中时,对属性访问器的调用有时看起来像方法

// "Reflected" example
class Class1 {
public bool Boolean { get; set;}
}

class Class2 {
public Class2() {
var class1 = new Class1();
var boolean = class1.get_Boolean();
}
}

现在我很好奇,我在 Class1 中放置了一个具有类似签名的方法,它看起来像访问器的标准约定。

// "Hacked" example
class Class1 {
public bool get_Boolean() { return true; }
}

不知何故,C# 编译器仍然将 get_Boolean 视为一种方法。

将方法变成属性的神奇秘诀是什么?

最佳答案

如果您查看 IL,您会发现类似这样的内容:

.property instance string Source()
{
.get instance string System.Exception::get_Source()
.set instance void System.Exception::set_Source(string)
}

.method public hidebysig specialname newslot virtual
instance string get_Source () cil managed
{
...
}

.method public hidebysig specialname newslot virtual
instance void set_Source (
string 'value'
) cil managed
{
...
}

所以“魔法”是一个 .property 成员,它将两个方法粘合在一起。

关于c# - 使属性与 CLR 一起工作的魔力是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13087571/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com