5

有一个类具有一个属性:

public class BaseClass
{
  public virtual string Property1 { get; set; }
}

现在我创建一个带有一些方法覆盖的派生类型:

[Test]
public void name ()
{
  var assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly (new AssemblyName ("Test"), AssemblyBuilderAccess.RunAndSave);
  var moduleBuilder = assemblyBuilder.DefineDynamicModule ("Test.dll");
  var derivedBuilder = moduleBuilder.DefineType ("DerivedClass", TypeAttributes.Public, typeof (BaseClass));

  const MethodAttributes methodAttributes = MethodAttributes.Private | MethodAttributes.Virtual | MethodAttributes.SpecialName | MethodAttributes.NewSlot;

  var getterOverride = derivedBuilder.DefineMethod (
      "get_Property1",
      methodAttributes,
      typeof (string),
      Type.EmptyTypes);
  var getterILGenerator = getterOverride.GetILGenerator();
  getterILGenerator.Emit (OpCodes.Ldnull);
  getterILGenerator.Emit (OpCodes.Ret);
  derivedBuilder.DefineMethodOverride (getterOverride, typeof (BaseClass).GetMethod ("get_Property1"));

  var setterOverride = derivedBuilder.DefineMethod (
      "set_Property1",
      methodAttributes,
      typeof (void),
      new[] { typeof (string) });
  var setterILGenerator = setterOverride.GetILGenerator ();
  setterILGenerator.Emit (OpCodes.Ret);
  derivedBuilder.DefineMethodOverride (setterOverride, typeof (BaseClass).GetMethod ("set_Property1"));

  var derivedType = derivedBuilder.CreateType();
  var props = derivedType.GetProperties (BindingFlags.Public | BindingFlags.NonPublic | BindingFlags.Instance);

  assemblyBuilder.Save ("Test.dll");

  Assert.That (props, Has.Length.EqualTo (1));
}

生成的类型不再包含该属性。奇怪的是,如果您将 更改为至少一个方法定义,该属性会再次methodAttributes出现MethodAttributes.Public

看起来像一个错误?

编辑: peverify 不会给出错误。

编辑:(Fabian Schmied 的重要评论)

ECMA-335 Partition II, 10.3.3:“如果一个类型通过 MethodImpl 覆盖了继承的方法,它可以扩大或缩小该方法的可访问性。”

4

1 回答 1

4

由于规范(ECMA-335,II.10.3.3)明确允许人们缩小通过 MethodImpl 覆盖的方法的可见性(“显式覆盖”,由 Reflection.Emit 通过 TypeBuilder.DefineMethodOverride 表示),我相信这确实是一个反射实现中的错误,应通过Microsoft Connect报告。

于 2012-08-07T13:12:38.017 回答