ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

CodeGo.net>如何定义“值”属性设置器参数

2019-11-10 19:09:48  阅读:178  来源: 互联网

标签:reflection-emit cil c


使用以下C#代码:

public interface IFoo
{
    int Bar
    {
        get;
        set;
    }
}

属性设置器签名编译为:

.method public hidebysig specialname newslot abstract virtual 
    instance void set_X (
        int32 'value'
    ) cil managed 
{
}

用ILSpy或ildasm检查时.

如果我尝试使用System.Reflection.Emit API生成相同的方法签名,则生成的输入参数名称为空:

.method public hidebysig specialname newslot abstract virtual 
    instance void set_X (
        int32 ''
    ) cil managed 
{
}

(由ilspy生成的签名)

…或看似生成的参考名称(在这种情况下为A_1):

.method public hidebysig newslot specialname abstract virtual 
    instance void  set_X(
        int32 A_1
    ) cil managed
{
}

(由ildasm生成的签名)

如何像C#编译示例中那样为输入参数赋予名称“值”?

这是我用来生成setter的代码:

PropertyBuilder property = typeDef.DefineProperty("X", PropertyAttributes.HasDefault, CallingConventions.HasThis, typeof(int), null);

MethodAttributes ma = MethodAttributes.Public 
                    | MethodAttributes.HideBySig 
                    | MethodAttributes.NewSlot 
                    | MethodAttributes.SpecialName 
                    | MethodAttributes.Abstract 
                    | MethodAttributes.Virtual;
MethodBuilder setMethod = typeDef.DefineMethod("set_X", ma, CallingConventions.HasThis, null, new[] { typeof(int) });

property.SetSetMethod(setMethod);

即使当我明确尝试定义参数名称时,结果仍然相同:

MethodBuilder setMethod = typeDef.DefineMethod("set_X", ma, CallingConventions.HasThis, null, new[] { typeof(int) });

ParameterBuilder pb = setMethod.DefineParameter(0, ParameterAttributes.None, "value");

property.SetSetMethod(setMethod);

解决方法:

我认为您必须对第一个参数使用索引1.从MethodBuilder.DefineParameter Method的msdn条目中:

Remarks

[…]

Parameter numbering begins with 1, so position is 1 for the first parameter. If position is zero, this method affects the return value.

标签:reflection-emit,cil,c
来源: https://codeday.me/bug/20191110/2014473.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有