CustomAttributeFormatException:指定自定义属性的二进制格式无效

时间:2014-08-06 06:51:36

标签: .net attributes params

我们发现了一些与属性相关的奇怪行为,我们只有一个问题:为什么? 例。 首先,我们在下一个签名中有一些属性:

public class Myc : Attribute
    {
        public Myc( bool b = false, params int[] a )
        {
            Console.WriteLine( "in ctor" );
        }

    }

当我们尝试调用没有参数的构造函数时,下一个:

class Program
    {
        [Myc]
        static void Main( string[] args )
        {
            Console.ReadKey();
        }
    }

我们得到了下一个例外: System.Reflection.CustomAttributeFormatException:指定自定义属性的二进制格式无效。

为什么会这样?

1 个答案:

答案 0 :(得分:7)

不确定原因是什么;在我自己的测试中,它似乎与一个或多个默认参数和一个" params"的组合有关。构造函数定义中的参数。但是,如果它阻止你,那就是一个懒惰的解决方法:

public class Myc : Attribute
{
    public Myc (params int[] a) : this(false) {}

    public Myc( bool b, params int[] a )
    {
        Console.WriteLine( "in ctor" );
    }
}

A" params"具有非违约价值的参数和" params"单独论证似乎都很好。

不完全是一种解释,但是呃......