Chinaunix首页 | 论坛 | 博客
  • 博客访问: 5226725
  • 博文数量: 1696
  • 博客积分: 10870
  • 博客等级: 上将
  • 技术积分: 18357
  • 用 户 组: 普通用户
  • 注册时间: 2007-03-30 15:16
文章分类
文章存档

2017年(1)

2016年(1)

2015年(1)

2013年(1)

2012年(43)

2011年(17)

2010年(828)

2009年(568)

2008年(185)

2007年(51)

分类: C/C++

2010-09-13 15:43:24

There's a lot of difference between a C# property and attribute. A property lets you get/set data in your class.  However, an attribute allows you to decorate elements of your code with declarative information.  i.e. here's  a class with three properties:

public class Customer
{
    public string Name { get; set; }
    public string Email { get; set; }
    public string Address { get; set; }
}

and you use it like this:

var cust = new Customer();

cust.Name = "Some Name";

Console.WriteLine("Name: " + cust.Name);

However, an attribute is much different and the attributes you use depend on the tool you are using.  For example, if you had a method you wanted to deprecate from your application, you could use the Obsolete attribute like this:

[Obsolete("Method deprecated - Please use MethB instead")]
public void MethA() { ... }

If you were writing unit tests in VS2008, you would use Test and TestMethod attributes like this:

[Test]
public class MyTestClass
{
    [TestMethod]
    public void MyTestMethod() { .... }
}

To summarize, attributes support tools that operate on your code, but properties define the state of an object and there is no logical comparison between the two.

Because of this difference in purpose and the fact that you asked a question that sounds like you feel they are similar, I wonder what you meant by the term "attribute".  It almost sounds like you were really wanting to know the difference between fields and properties.  Just in case, that was really your question: a field gives calling code direct access to the data in your class, but a property allows you to control access to that value.  If the underlying representation of the data changes, then a field would cause calling code to break, which could cause a rippling effect through your code for trying to fix the change.  If someone else's code depends on that field, then their code would break, which means that you might not be able to change your class.  If you use a property, you can manipulate the representation of the data in the property accessors if there ever was a change and calling code would never know, which gives you more maintainable code.  For this reason, I tend to use properties as a general preference over fields.  I won't go as far as to suggest that you should never use a *public* field, because someone might have a valid use case for it (in a limited scenario), but I still think that for general software development the property will serve you better.
阅读(1750) | 评论(0) | 转发(0) |
给主人留下些什么吧!~~