简体   繁体   English

为什么我应该在属性访问器中使用私有变量?

[英]Why should I use a private variable in a property accessor?

Sorry If I am being noob, I have this doubt, why do we use private variables and set them using properties ? 对不起如果我是菜鸟,我有这个疑问,为什么我们使用私有变量并使用属性设置它们?

Why can't we just use properites alone ? 为什么我们不能单独使用专业人士?

I am talking about situations like this 我在谈论这样的情况

private string _testVariable;

public string MyProperty
{
    get { return _testVariable;}
    set {_testVariable = value;}
}

I am thinking of simply using 我在考虑简单地使用

public string MyProperty { get; set; } 

Why redundant private variable? 为什么冗余私有变量? are these two strategies different ? 这两种策略有什么不同? can anyone please throw some light on this. 任何人都可以请注意这一点。

Thanks 谢谢

Your examples are semantically the same. 您的示例在语义上是相同的。 The concise property declaration syntax (just having { get; set; } ) is a shortcut available in C# 3.0. 简洁的属性声明语法(只有{ get; set; } )是C#3.0中提供的快捷方式。 The compiler actually creates a private backing variable and a simple getter and setter as in your first example. 编译器实际上创建了一个私有后备变量和一个简单的getter和setter,如第一个示例所示。

If all you're doing is creating a getter and setter (and nothing actually happens when either occurs), then the concise syntax is a good option. 如果你所做的只是创建一个getter和setter(并且在发生任何事情时都没有发生任何事情),那么简洁的语法是一个不错的选择。 If you have to perform any other actions (redraw a control, for example) when you set the value, then the full syntax is required. 如果在设置值时必须执行任何其他操作(例如重绘控件),则需要完整语法。

Why redundant private variable? 为什么冗余私有变量? are these two strategies different ? 这两种策略有什么不同? can anyone please throw some light on this. 任何人都可以请注意这一点。

If all your doing is reading/writing a variable, then no. 如果你所做的只是读/写变量,那么没有。 Otherwise, there's two reasons why you'd want a private variable: 否则,您需要私有变量的原因有两个:

Data validation 数据验证

// Data validation
public class IntWrapper
{
    private int _value;
    public int Value
    {
        get { return _value; }
        set
        {
            if (value < 0) { throw new Exception("Value must be >= 0"); }
            _value = value;
        }
    }
}

Getter/setter wraps up an underlying data store Getter / setter包装底层数据存储

public class StringBuffer
{
    List<char> chars = new List<char>();

    // Wraps up an underlying data store
    public string Value
    {
        get { return new String(chars.ToArray()); }
        set { chars = new List<char>(value.ToCharArray()); }
    }

    public void Write(string s) { Write(chars.Count, s); }

    public void Write(int index, string s)
    {
        if (index > chars.Count) { throw new Exception("Out of Range"); }
        foreach(char c in s)
        {
            if (index < chars.Count) { chars[index] = c; }
            else { chars.Add(c); }
            index++;
        }
    }
}

The second example that you give: 你给出的第二个例子:

public string MyProperty { get; set; }

Is only available in later versions of the .Net framework (v3.0 onwards I believe) 仅在.Net框架的更高版本中可用(我相信v3.0以后)

The first example allows you to set breakpoints on the return and assignment statements, causing your debugger to break when the property is assigned / read. 第一个示例允许您在return和赋值语句上设置断点,从而导致调试器在分配/读取属性时中断。

The 1st code snip allws you to modify some private class state. 第一个代码剪辑会让您修改一些私有类状态。 Wrapping private state in a property is nice because it hides the implementation. 在属性中包装私有状态很好,因为它隐藏了实现。 Later you can change the implementation and the property (external interface) may remain unchanged. 稍后您可以更改实现,属性(外部接口)可能保持不变。

For example, suppose instead of setting a single string within the setter, you set the string in a private store of some sort. 例如,假设您不是在setter中设置单个字符串,而是在某种私有存储中设置字符串。 You write it to a file, or write it to shared memory. 您将其写入文件,或将其写入共享内存。 Or maybe you compute the hash of the string only, and don't store it at all, as you might do with a password. 或者,您可能只计算字符串的哈希值,并且根本不存储它,就像您可能使用密码一样。

The auto properties in your 2nd code snip are not related to the private variable at all. 第二个代码片段中的自动属性与私有变量无关。 The auto-property design, like the explicit property design used in the first snip, allows future modification. 自动属性设计(如第一个剪辑中使用的显式属性设计)允许将来进行修改。 As part of that modification, for example, you could convert from auto properties to explicitly implemented properties. 例如,作为修改的一部分,您可以从自动属性转换为显式实现的属性。

Mashesh, We all had to start somewhere! Mashesh,我们都必须从某个地方开始! You asked about private vars vs properties with this ex: 你用这个ex询问了私有变量vs属性:

private string _testVariable;

public string MyProperty
{
    get { return _testVariable;}
    set {_testVariable = value;}
}

-or-

public string MyProperty { get; set; }

Did you consider: 你考虑过:

public string MyProperty { get; private set; }

You can apply scope to property getters/setters . 您可以将范围应用于属性getter / setter。 . . . cool stuff. 很酷的东西。 Oh yeah . 哦耶 。 . . when using this type of property within the defining class (like in a constructor) prepend it with a 'this.' 当在定义类中使用这种类型的属性时(比如在构造函数中),在它前面加上'this'。 - so an assignment would look like 'this.MyProperty = "An Assigned String";'. - 所以赋值看起来像'this.MyProperty =“一个赋值字符串”;'。 This makes your intentions much more clear . 这使得你的意图更加清晰。 . .

I HATE backing variables when they are not needed it is causes more complexity then necessary. 我讨厌在不需要时支持变量,这会导致必要时更复杂。

Obviously if you have the need to do something special in the getter or setter then the full semantic form should be used and not the sugar. 显然,如果你需要在getter或setter中做一些特殊的事情,那么应该使用完整的语义形式而不是糖。

Also I like to use properties as a method of debugging how the property gets set or gets used sometimes this isn't as obvious because of reflection and that is one reason I like to use them. 此外,我喜欢使用属性作为调试属性如何设置或使用的方法,有时这不是因为反射而显而易见,这是我喜欢使用它们的一个原因。

I find it frustrating trying to debug code when there is a possibility that the backing variable maybe accessed either internally in the class by the property it self or the backing variable and nothing tells the coder the right way to access. 当有可能在类中内部通过属性本身或后备变量访问支持变量并且没有任何东西告诉编码器正确的访问方式时,我发现尝试调试代码是令人沮丧的。

You can access the backing variable internally as well as the property so which is the right way? 您可以在内部访问支持变量以及属性,这是正确的方法吗? It is not obvious... 这不明显......

Property is basically the wrapper around a field. 属性基本上是一个字段的包装器。 This wrapper enables to use the variable from outside world. 这个包装器可以使用来自外部世界的变量。 In C#3.0 you can simply declare a property like public string MyProperty { get; set; } 在C#3.0中,您可以简单地声明一个属性,如public string MyProperty { get; set; } public string MyProperty { get; set; } public string MyProperty { get; set; } The compiler declares a private variable automatically and get set methods for that also. public string MyProperty { get; set; }编译器会自动声明一个私有变量,并获得也set方法。 If you need to perform any calculation inside the class that is declaring the property, then you should use the private field for that. 如果您需要在声明属性的类中执行任何计算,那么您应该使用私有字段。

Sometimes you don't know when you first write the code whether you may be adding some more code later that needs to use the private variable. 有时您不知道何时第一次编写代码,是否可能在以后添加一些需要使用私有变量的代码。 Sure, you can add it later if needed. 当然,如果需要,您可以稍后添加。 I just automatically create the private variable, assuming that it will be used later. 我只是自动创建私有变量,假设它将在以后使用。

This may be more relevant in large enterprise apps or rapidly evolving apps (agile) where the full implementation may not be known during the initial coding. 这在大型企业应用程序或快速发展的应用程序(敏捷)中可能更为相关,其中在初始编码期间可能不知道完整实现。

This isnt related to C# the langugage, but more the application. 这与C#langugage无关,但更多的是应用程序。

One reason to use properties, is that its treated as "Special" in many frameworks. 使用属性的一个原因是它在许多框架中被视为“特殊”。 For example, Silverlight and WPF will bind to properties and not to fields 例如,Silverlight和WPF将绑定到属性而不绑定到字段

暂无
暂无

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

相关问题 C#访问者应该使用私有变量还是动态计算? - Should a C# accessor use a private variable or calculate on the fly? 为什么不推荐使用私人访问者? - Why is Private Accessor deprecated? 使用 C# 为什么要使用访问器而不是仅将变量设置为等于属性? - With C# Why would you use an accessor instead of just setting the variable equal to the property? 使用私有访问者设置属性值 - Set value of property with private accessor 如果我的课程有一个带有私有字段用于存储的属性,我应该使用私有字段还是该属性在构造函数中对其进行初始化? - If my class has a property with a private field for storage, should i use the private field or the property to initialize it in the constructor? 是不是我不应该在属性访问器中做“长时间运行”的事情? - Is it true I should not do “long running” things in a property accessor? 我应该使用带有公共获取方法的私有属性/字段还是直接使用公共属性进行正确封装? - Should I use a private property/field with a public getter method or directly use a public property for proper encapsulation? 我应该在声明该属性的类中使用公共属性的私有字段吗? - Should I use a private field of a public property inside a class where I declare that property? ReadOnly我应该在vb.net中使用私有集的属性或属性? - ReadOnly Property or property with private set I should use in vb.net? 为什么我不能为重写属性添加set访问器? - Why can I not add a set accessor to an overriden property?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM