c# - Reflection.Emit 中的 IEnumerable 属性创建

标签 c# .net reflection reflection.emit

我正在尝试创建 IEnumerable<AnotherDynamicType> 类型的属性使用Reflection.Emit .

我有一个辅助方法,可以很好地添加属性,接受类型作为输入:

public void AddProperty(TypeBuilder typeBuilder, string propertyName, Type type) 
{
    ....
}

可以这样调用:

AddProperty(typeBuilder,"MyPropertyName",typeof(string));

但是现在我想向类添加一个属性:

public IEnumerable<AnotherDynamicType> MyList {get;set;}

假设目标 AnotherDynamicType ,如何定义该调用属性的“类型”也是动态创建的吗?

以下内容无法编译:

AddProperty(typeBuilder,"MyPropertyName",typeof(IEnumerable<typeof(anotherDynamicType)>));

最佳答案

您可以使用Type.MakeGenericType :

var anotherTypeEnumerable = typeof(IEnumerable<>)
                            .MakeGenericType(anotherDynamicType);

关于c# - Reflection.Emit 中的 IEnumerable 属性创建,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31458669/

相关文章:

C# 反射 SetValue() 找不到设置访问器

c# - 分离表达式<Func<T, object>>

c# - 在 vnext 应用程序中测试 IActionResult 内容

c# - .NET GDI+ 中的字体大小差异?

c# - 如何创建委托(delegate)来读取匿名类型的属性?

Java反射,从父类(super class)调用方法?

c# - Lucene:查找最接近的数字

c# - 在 ASP.Net 中使用 JavaScript

c# - 如何在Unity Editor中运行两个游戏窗口

c# - 信号R错误! signalr/negotiate 收到 "403 - Forbidden: Access is denied."错误