为什么您使用C#的getter / setter方法的私有变量? [英] Why do you use private variables with C# getter/setters?

查看:125
本文介绍了为什么您使用C#的getter / setter方法的私有变量?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我看到这一切的时候:

    private int _myint;

    public int MyInt
    {
        get
        {
            return _myint;
        }
        set
        {
            _myint = value;
        }
    }



对我来说这似乎是相同的:

To me this seems identical to:

    public int MyInt{ get; set; }



那么,为什么每个人都做前...为什么私人VAR可言?!

So why does everyone do the former... WHY THE PRIVATE VAR AT ALL?!

推荐答案

首先,这是新的C#3.0,它不在身边之前。第二,如果你想要的任何自定义逻辑添加到您的getter和setter方法,你别无选择。所以,是的,在你的榜样那里没有自定义的逻辑,这是同样的事情(实际上,编译器生成你在幕后),但如果你想提高一样,例如事件或任何东西,你必须要明确一下吧。

First of all, this is new to C# 3.0, it wasn't around before that. Second, if you want to add any custom logic to your getter and setters, you have no choice. So yes, in your example where there's no custom logic, it's the same thing (in fact the compiler generates that for you behind the scenes) but if you want to raise an event for example, or anything like that, you have to be explicit about it.

这篇关于为什么您使用C#的getter / setter方法的私有变量?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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