c# - 如何定义 'value'属性 setter 参数

标签 c# cil reflection.emit

使用以下 C# 代码:

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

属性 setter 签名编译为:

.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# 编译示例中那样为输入参数指定名称“value”?


这是我用来生成 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.

关于c# - 如何定义 'value'属性 setter 参数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47682484/

相关文章:

c# - datagrid 获取单元格索引

c# - 在 IL 中对空引用调用实例方法

c# - 如何反编译 .net framework 的 IL 代码

.net - AssemblyBuilder 引用程序集

c# - ASP.NET 路由在内部是如何工作的?

c# - 你如何在 xaml 的 ListView 中拉伸(stretch)图像?

c# - 使用反射进行异步编程

c# - 如何使用 Reflection Emit 定义具有相同名称和不同类型参数的多个类型?

c# - 如何获取 T 函数中使用的属性名称字符串

.net - 修改现有的 .NET 程序集