发出属性的显式接口实现

问题描述 投票:0回答:1

目标

所以我想做的是在运行时使用TypeBuilder类创建一个类型。我希望从中实现运行时类型的接口如下所示。

public interface ITest
{
    int TestProperty { get; }
}

应生成的类型应如下所示:

internal class Test : ITest
{
    int ITest.TestProperty { get => 0; }
}

接口的显式实现不是真正必需的,但这是我发现最多资源的地方。


现在为实际代码

var assemblyName = new AssemblyName("AssemblyTest");
var assemblyBuilder = AssemblyBuilder.DefineDynamicAssembly(assemblyName, AssemblyBuilderAccess.Run);
var module = assemblyBuilder.DefineDynamicModule(assemblyName.Name + ".dll");

var typeBuilder = module.DefineType("TestType", TypeAttributes.NotPublic | TypeAttributes.BeforeFieldInit | TypeAttributes.AutoClass | TypeAttributes.AnsiClass | TypeAttributes.Class, null, new[] { typeof(ITest) });

var prop = typeBuilder.DefineProperty("ITest.TestProperty", PropertyAttributes.HasDefault, typeof(int), null);

var propGet = typeBuilder.DefineMethod("ITest.get_TestProperty", MethodAttributes.Private | MethodAttributes.SpecialName | MethodAttributes.NewSlot | MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.Final);

var propertyGetIL = propGet.GetILGenerator();

propertyGetIL.Emit(OpCodes.Ldc_I4_0);
propertyGetIL.Emit(OpCodes.Ret);

prop.SetGetMethod(propGet);

typeBuilder.DefineMethodOverride(propGet, typeof(ITest).GetProperty("TestProperty").GetGetMethod());

var type = typeBuilder.CreateType();

仅作为代码的简短说明。

  1. 创建DynamicAssembly /模块/类
  2. 创建背景字段和属性本身
  3. 为属性创建Get方法的内容
  4. 将属性标记为接口的implementation
  5. 创建新类型

但是CreateType方法向我抛出以下内容:

主体的签名与方法实现中的声明不匹配。类型:“ TestType”。程序集:“ AssemblyTest,版本= 0.0.0.0,文化=中性,PublicKeyToken =空”。'

我真的不确定如何实现该属性以及其原因是什么。

c# reflection reflection.emit typebuilder
1个回答
0
投票

您在定义get方法时缺少返回类型。您需要使用different overloadDefineMethod指定它:

var propGet = typeBuilder.DefineMethod("ITest.get_TestProperty", 
  MethodAttributes.Private | MethodAttributes.SpecialName | MethodAttributes.NewSlot | 
  MethodAttributes.HideBySig | MethodAttributes.Virtual | MethodAttributes.Final,
  typeof(int), // <--- return type
  Type.EmptyTypes // <-- parameter types (indexers)
);
© www.soinside.com 2019 - 2024. All rights reserved.