简体   繁体   English

使用Reflection.Emit创建具有属性的接口

[英]Create an interface with properties with Reflection.Emit

I need to generate an interface. 我需要生成一个接口。 I'va a problem to generate (emit) the virtual properties. 我在生成(发出)虚拟属性时遇到问题。 It seems they are not generated. 看来它们不是生成的。

I figure out I'm doing something wrong: 我发现我做错了什么:

private static TypeBuilder getTypeBuilder()
    {
        var typeSignature = "DynamicDigitalInput";
        var an = new AssemblyName(typeSignature);

        AssemblyBuilder assemblyBuilder = AppDomain.CurrentDomain.DefineDynamicAssembly(an, AssemblyBuilderAccess.Run);
        ModuleBuilder moduleBuilder = assemblyBuilder.DefineDynamicModule("DynamicDomain");
        TypeBuilder tb = moduleBuilder.DefineType(typeSignature
                            , TypeAttributes.Public |
                            TypeAttributes.Interface |
                            TypeAttributes.Abstract |
                            TypeAttributes.AutoClass |
                            TypeAttributes.AnsiClass |
                            TypeAttributes.BeforeFieldInit |
                            TypeAttributes.AutoLayout
                            , null);

        return tb;
    }

    private static void createProperty(TypeBuilder tb, string propertyName, Type propertyType)
    {

        PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);
    }

In order to generate the interface: 为了生成接口:

TypeBuilder tb = getTypeBuilder();
createProperty(tb, "p1", String.GetType());
createProperty(tb, "p2", Int32.GetType());

When I perform this: 当我执行此操作时:

Type i = tb.CreateType();
System.Reflection.PropertyInfo p1 = type.GetProperty("p1");

p1 is null . p1null

What am I doing wrong? 我究竟做错了什么?

The property is not defined correctly. 该属性未正确定义。 In order for GetProperty to work, the property must have at least one public getter or setter. 为了使GetProperty起作用,该属性必须至少具有一个公共获取程序或设置程序。 Right now, is does not have even one getter or setter, so they never can be public. 现在,甚至没有一个getter或setter,所以它们永远不会公开。

So, you have to create a public get-method and/or a public set-method (using the MethodBuilder). 因此,您必须创建一个公共的get方法和/或一个公共的set方法(使用MethodBuilder)。 Try this: 尝试这个:

private static void createProperty(TypeBuilder tb, string propertyName, Type propertyType)
{
    PropertyBuilder propertyBuilder = tb.DefineProperty(propertyName, PropertyAttributes.HasDefault, propertyType, null);
    MethodBuilder methodBuilder = tb.DefineMethod("get_" + propertyName, MethodAttributes.Virtual | MethodAttributes.Abstract | MethodAttributes.Public);
    propertyBuilder.SetGetMethod(methodBuilder);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM