在C#中的属性 [英] properties in C#

查看:178
本文介绍了在C#中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我们为什么能写出

 公众诠释RetInt 
{
获取;设置;
}



而不是

 公众诠释RetInt 
{
{返回someInt;}集合{someInt =值;}
}

什么是两者之间?


解决方案
<区别p>此功能称为自动实现的属性,并与C#3.0

$ b介绍
$ b

在C#3.0及更高版本,自动实现的属性使
财产申报时,不需要额外的逻辑
在属性访问器更简洁。它们还使客户端代码来创建
的对象。当你声明一个属性作为显示在下面的
为例,在编译器创建,只能通过属性的get访问并设置
访问一个私人的,匿名的支持字段




 类客户
{
//自动 - IMPL属性琐碎get和set
公共双TotalPurchases {搞定;组; }
公共字符串名称{;组; }
公众诠释客户ID {搞定;组; }

有关您的问题




两者有什么区别呢?




在你的情况,没有。既然你没有做任何事情,而设置或检索的价值,但假设你想要做一些验证或要执行其他类型的检查的话:

 私人诠释someInt; 
公众诠释RetInt
{
得到
{
如果(someInt大于0)
返回someInt;
,否则
返回-1;
}
集合{someInt =价值; } //同一种检查/验证可以在这里完成
}



上面可以'T与自动实现的属性来完成。



还有一件事,你可以看到不同的是初始化一个自定义类类型属性时。



如果您有 MyClass的
名单则在正常财产的情况下,其支持字段可以初始化/实例化比其他构造。

 私人列表< MyClass的>名单=新名单,LT; MyClass的>(); 
公开名单< MyClass的>表
{
{返回清单; }
集合{=值; }
}

在自动实现的属性的情况下,

 公开名单< MyClass的> SomeOtherList {搞定;组; } 

您只能初始化 SomeOtherList 的构造,你不能这样做,在现场级。


Why are we able to write

public int RetInt
{
   get;set;
}

instead of

public int RetInt
{
   get{return someInt;}set{someInt=value;}
}

What is the difference between the two?

解决方案

This feature is called Auto implemented properties and introduced with C# 3.0

In C# 3.0 and later, auto-implemented properties make property-declaration more concise when no additional logic is required in the property accessors. They also enable client code to create objects. When you declare a property as shown in the following example, the compiler creates a private, anonymous backing field that can only be accessed through the property's get and set accessors.

class Customer
{
    // Auto-Impl Properties for trivial get and set 
    public double TotalPurchases { get; set; }
    public string Name { get; set; }
    public int CustomerID { get; set; }

For your question

What is the difference between the two?

In your case, none. Since you are not doing anything while setting or retrieving the value, but suppose you have want to do some validation or want to perform other types of check then :

private int someInt;
public int RetInt
{
    get
    {
        if (someInt > 0)
            return someInt;
        else
            return -1;
    }
    set { someInt = value; } // same kind of check /validation can be done here
}

The above can't be done with Auto implemented properties.

One other thing where you can see the difference is when initializing a custom class type property.

If you have list of MyClass Then in case of Normal property, its backing field can be initialized/instantiated other than the constructor.

private List<MyClass> list = new List<MyClass>();
public List<MyClass> List
{
    get { return list; }
    set { list = value; }
}

In case of Auto implemented property,

public List<MyClass> SomeOtherList { get; set; }

You can only initialize SomeOtherList in constructor, you can't do that at Field level.

这篇关于在C#中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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