2010-08-24 38 views
10

什么是[和]在C#中?它是干什么用的?这是什么意思?什么是[和]在C#中?

例如

[DefaultValue(null)] 
[JsonName("name")] 
public string Name 
{ 
    get 
    { 
     if (this.name == null) 
     { 
      return String.Empty; 
     } 
     return this.name; 
    } 
} 

回答

16

即一个Attribute。他们自己什么都不做,只是装饰代码。但是代码可以在运行时发现属性并对它们做出反应。

+1

也用于阵列,索引,指针:http://msdn.microsoft.com/en-us/library/a3hd7ste.aspx – cofiem 2010-08-24 13:46:18

+0

+1链接到文档 – Mizipzor 2010-08-24 13:46:23

+1

@cofiem:这就是所谓的'索引器' – abatishchev 2010-08-24 13:47:02

2

它被称为属性,用于将元数据添加到您的代码中。

3

在这种情况下,它是一种在方法和类上定义属性的方法。属性就像特殊的注释,除非它们被编译到dll中并且可以在运行时查询。

0

[]是方括号。在你的使用中,它们表示一个属性。在其他情况下使用时,它们会指示某种索引。

实例

int[] intArray = new int[6]; //Initializes an array of 6 integers 
intArray[0] = 1; //Assigns the value 1 to the first (zero-based) index of intArray 

string connString = ConfigurationManager.ConnectionStrings["default"].ConnectionString; 
//The above uses "text indexing" to find the connection string in your App.config 
// or Web.config with a key with the provided string (in this case "default") 

也可以使用正方形brakets抓住由密钥名称词典项目,元件中的集合,如数据集或者用索引号或姓名等