简体   繁体   English

C#对象中[key]的目的是什么?

[英]What is the purpose of [key] in a C# object?

I'm trying to code a WCF RIA class for the first time in C# (also my first time with the language), just to join some tables for a LightSwitch data source. 我正在尝试使用C#首次编写WCF RIA类(这也是我第一次使用该语言),只是为了为LightSwitch数据源加入一些表。 Following the example code , I created the following class to return my rows of data: 按照示例代码 ,我创建了以下类以返回数据行:

public class StudentTerm
{
    [Key]
    public string TermCode { get; set; }
    public string StudentID { get; set; }
    public decimal? TermGPA { get; set; }
    public decimal? CumulativeGPA { get; set; }
}

But I'm curious -- what is the purpose of the [Key] typedef? 但是我很好奇-[Key] typedef的目的是什么? Does it apply only to TermCode in my example, or to the entire class? 它仅适用于我的示例中的TermCode还是整个类?

Key on top of TermCode is called property attribute. Key之上TermCode被称为property属性。
Attributes provide a powerful method of associating declarative information with C# code (types, methods, properties, and so forth). 属性提供了一种将声明性信息与C#代码(类型,方法,属性等)相关联的强大方法。 Once associated with a program entity, the attribute can be queried at run time and used in any number of ways. 一旦与程序实体相关联,就可以在运行时查询该属性,并以多种方式使用它。
More on attributes you can find here. 有关属性的更多信息,请参见此处。

In this speciffic case we are talking about WCF RIA Services attribute. 在这种特殊情况下,我们谈论的是WCF RIA服务属性。
In WCF RIA Services each entity must have a primary key defined and you designate a property as the primary key with the [Key] attribute. 在WCF RIA Services中,每个实体都必须定义一个主键,并且您可以使用[Key]属性指定一个属性作为主键。 You can decorate multiple properties if the class has a composite primary key. 如果类具有复合主键,则可以修饰多个属性。

As @LIUFA says above, Key is an Attribute. 就像@LIUFA所说的那样, Key是一个属性。 It's full name is System.ComponentModel.DataAnnotations.KeyAttribute This is to denote that the Id field is the primary key of the underlying data store. 它的全名是System.ComponentModel.DataAnnotations.KeyAttribute这表示Id字段是基础数据存储区的主键。

In a more general sense, an Attribute can decorate a class, method, property, or assembly. 在更一般的意义上, Attribute可以修饰类,方法,属性或程序集。 They don't do anything on their own, but are used by other code to "mark" things. 它们自己不会做任何事情,但是被其他代码用来“标记”事物。

You should probably check the msdn libraries for an answer: http://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.keyattribute(v=vs.110).aspx 您可能应该检查msdn库以获得答案: http : //msdn.microsoft.com/zh-cn/library/system.componentmodel.dataannotations.keyattribute( v=vs.110) .aspx

And yes, it only applies to TermCode . 是的,它仅适用于TermCode Class attributes are placed just above the class definition. 类属性位于类定义上方。 Also Key Is a property of field attribute so it can't be applied to a class 另外Key是field属性的属性,因此无法应用于类

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM