属性构造函数中的可选参数不编译:S [英] Optional parameters in constructor of attributes do not compile :S

查看:107
本文介绍了属性构造函数中的可选参数不编译:S的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢新的.NET 4.0可选参数功能,但是最近遇到了一个我不明白的限制.

考虑以下简单属性:

I''m fond of the new .NET 4.0 optional parameters feature, but I''ve recently came across a limitation I do not understand.

Consider the following simple attribute:

class SomeAttribute : Attribute
{
	public SomeAttribute(string someString = null)
	{
	}
}



当我尝试在语句[SomeAttribute()]中使用属性时,在编译时会产生以下错误:

属性参数必须是属性参数类型的常量表达式,typeof表达式或数组创建表达式."

这让我感到奇怪,因为默认参数是一个常量表达式....甚至更陌生的是:
当我将null更改为""或删除部件 : Attribute并调用实例new SomeAttribute()时,代码可以编译.我一无所知...

有人可以解释一下为什么会生成此错误,而不是其他情况吗?
除了创建各种构造函数重载(例如在4.0之前的.NET版本中)之外,还有其他变通办法吗?



When I try to use the attribute in the statement [SomeAttribute()], the following error is generated on compiling:

"An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type."

This strikes me as odd, since the default argument IS a constant expression.... And even stranger is the following:
The code can compile when I change null to "", or when I remove the part : Attribute, and call for instance new SomeAttribute(). I''m clueless....

Can someone explain me why this error is generated and not in the other case?
And are there any workarounds, besides creating all sorts of constructor overload(like in .NET versions before 4.0)?

推荐答案

对我来说就像一个编译器错误,值得在Connect上进行报告.同时,这是一种解决方法:

Looks like a compiler bug to me, and worth reporting on Connect. Meanwhile, here''s a workaround:

class SomeAttribute : Attribute
{
    public const string pnull = null;

    public SomeAttribute(string someString = pnull)
    {
    }
}

[SomeAttribute()]
class App
{
    static void Main()
    {
    }
}


这篇关于属性构造函数中的可选参数不编译:S的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆