c# - 执行 XmlDocument 类型的 CustomAttributeBuilder 时出错

标签 c# reflection.emit getconstructor

我有以下代码作为使用 reflection.emit 生成接口(interface)的系统的一部分

class Class1:Attribute 
{
    public Class1(XmlDocument doc) 
    {
    }
}

var type = typeof(Class1);
var ctore = type.GetConstructor(new[] { typeof(XmlDocument) });
var cab = new CustomAttributeBuilder(ctore, new object[] { new XmlDocument() });

由于我不知道的原因,程序产生了一个错误:

In an argument, field, or property used designer custom attribute type is invalid.

最佳答案

请参阅 CustomAttributeBuilder 的备注部分文档:

The elements of the constructorArgs array are restricted to element types. They can be byte, sbyte, int, uint, long, ulong, float, double, String, char, bool, an enum, a type, any of the previous types that was cast to an object, or a single-dimension, zero-based array of any of the previous types.

您不能使用 XmlDocument 类型作为构造函数参数,因为它不在列表中。此限制来自 C# 属性参数限制。参见 17.1.3 Attribute parameter types可接受参数类型列表的 C# 规范部分:

  • 以下类型之一:bool、byte、char、double、float、int、long、short、string。
  • 类型对象。
  • 类型 System.Type。
  • 枚举类型,前提是它具有公共(public)可访问性和类型 它被嵌套(如果有的话)也具有公共(public)可访问性(第 17.2).
  • 上述类型的一维数组。

Constructor public Class1(XmlDocument doc) 对常规C#类完全有效,可以在属性类中声明。但是当你将属性应用于你的代码时,你不能使用它。这是任何属性类的目标。因此,尽管您可以声明这样的构造函数,但它对属性类没有任何意义。

关于c# - 执行 XmlDocument 类型的 CustomAttributeBuilder 时出错,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24629499/

相关文章:

c# - IL 使用 Reflection.Emit 调用带有 2 个数组参数的方法

java - 从泛型类型获取枚举类?

c# - Blazor 路由 - 导航到静态页面

reflection - 使用 mono.cecil 向 "existing"类型添加新的构造函数

c# - 为什么编码对象不保留在 native 代码中修改的值?

.net - 更改了 .Net 4 中泛型方法的 LdToken 行为?

java - 没有参数的getConstructor

java - 反射类型不匹配

c# - 读取反序列化的json文件

c# - 什么时候是 sqlchars 什么时候是 sqlstring?