C#与外地物业 [英] C# field vs. property

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

问题描述


可能重复:结果
在C#中物业和现场之间的差异






我认为基本属性( {获取;设置;} )其中相同的公共领域,具有了能够改变他们不破坏二进制兼容性的唯一优势。下面我来到这里 http://stackoverflow.com/a/8735303/331785 ,我找到了答案里面还有一个不利的特性。它们不能被引用,如果他们是值类型的访问。这是为什么,有?


解决方案

我发现同样是有什么其他的区别不利的属性。它们不能被引用,如果他们是值类型的访问。这是为什么




由于在幕后,属性仅仅是一个方法。如果你看一下IL,你会看到像 get_PropertyName set_PropertyName 方法。这样做的问题是,为了支持与引用工作,你就需要能够换来一个方法的引用。

  REF公共myProperty的牛逼
{
得到
{
返回REF _underlyingField;
}
}

这当然是的在CLR 东西完全可能的;而不是由C#语言曝光。



虽然是可能的,CLR需要一些调整,以保持它的验证。该属性的语法必须是支持。



然而,是任何有用的吗?正如你所说,一个领域可以做到这一点。如果你需要它;使用的字段。支持它需要占用大量的工作。可能有极少数情况下,它是合适的;并会创造一个只使用一个字段可能已经摆在首位更好的许多情况下。


Possible Duplicate:
Difference between Property and Field in C#

I thought that basic properties ({ get; set; }) where the same as public fields, with only the advantage of being able to change them without breaking binary compatibility. Following the answer I got here http://stackoverflow.com/a/8735303/331785, I found out there is also a disadvantage to properties. They cannot be accessed by reference if they are of a value type. Why is this, and what other differences are there?

解决方案

I found out there is also a disadvantage to properties. They cannot be accessed by reference if they are of a value type. Why is this

Because under the covers, a property is just a method. If you look at the IL, you'll see methods like get_PropertyName and set_PropertyName. The problem with that is in order to support working with references, you would need to be able to return a reference for a method.

public ref T MyProperty
{
    get
    {
         return ref _underlyingField;
    }
}

This of course, is something entirely possible in the CLR; but not exposed by the C# language.

Though it is possible, the CLR needs some tweaks to keep it as verifiable. The syntax for the property would have to support it to.

However, is any of that useful? As you stated, a field can do it. If you need it; use a field. Supporting it would take a lot of work. There are probably a very few cases where it is appropriate; and would create many cases where just using a field might have been better in the first place.

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

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