有一个类具有一个属性:
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 覆盖了继承的方法,它可以扩大或缩小该方法的可访问性。”