使用以下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.