简体   繁体   English

什么时候使用公共或私有财产?

[英]When to use the public or private property?

If I have a class like so: 如果我有这样的课程:

public class MyClass:INotifyPropertyChanged
{
private Visibility isVisible;
private ObservableCollection<string> names;

public Visibility IsVisible
{
get{ return isVisible;}
set { isVisible = value; OnPropertyChanged("IsVisible");}
}

public ObservableCollection<string> Names
{
get { return names;}
set { names = value; OnPropertyChanged("Names");}
}

//ctor
public MyClass(){
     names = new ObservableCollection<string>();
}


//INotifyPropertyChanged implementation
 public event PropertyChangedEventHandler PropertyChanged;
    private void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }

}

Before any one beheads me - I have done quite a bit of looking up and have found a mixed bag of answers... 在任何人将我斩首之前-我已经做了很多查找,找到了各种各样的答案...

  1. Do I modify the public or private properties/variables for use in my bindings? 我是否会修改用于绑定的publicprivate属性/变量? ie I have an issue where adding to names collection will trigger OnPropertyChanged and changing isVisible will NOT trigger OnPropertyChanged . 即我有一个问题,添加到names集合将触发OnPropertyChanged而更改isVisible不会触发OnPropertyChanged My assumption is that this is because names is an ObservableCollection where as isVisible is not but I am not sure... 我的假设是,这是因为names是一个ObservableCollection ,其中isVisible不是,但我不确定...

  2. If I am supposed to uses the public properties - what is the need for having the private ones? 如果我应该使用public财产,那么拥有私有财产又有什么需要?

You don't need a private property, only a private field would be enough so replace: 您不需要私有属性,只需一个私有字段就足够了,因此请替换:

private Visibility isVisible {get; set;}

with

private Visibility isVisible;

If I am supposed to uses the public properties - what is the need for having the private ones? 如果我应该使用公共财产,那么拥有私有财产又有什么需要?

You cannot use Auto-properties with INotifyPropertyChanged. 您不能将自动属性与INotifyPropertyChanged一起使用。 That is why you need a backing field for your property IsVisible . 这就是为什么您需要为属性IsVisible提供支持字段的原因。

See: An elegant way to implement INotifyPropertyChanged 请参阅: 一种实现INotifyPropertyChanged的优雅方法

So I think you are confusing Properties and Fields (aka variables). 所以我认为您混淆了属性和字段(又名变量)。

public class Example()
{

    public int FieldExample;

    private int _propertyExample;

    public int PropertyExample 
    {
        get
        {
            return _propertyExample;
        }
        set
        {
            _propertyExample = value;
        }
    }
}

In simple usage scenarios, the difference between a field and a property isn't obvious. 在简单的使用场景中,字段和属性之间的区别并不明显。 But properties have different plumbing under the hood that allows them to take advantage of reflection and binding. 但是属性在引擎盖下具有不同的管道,允许它们利用反射和绑定。 For WPF, this means you've got to have public properties. 对于WPF,这意味着您必须具有公共属性。 Best practice for a Public Property is associate it with a private (or protected) field - and that field name is usually either prefixed with an _ and/or starts with lower case character. 公共财产的最佳做法是将其与私有(或受保护)字段关联-该字段名称通常以_开头和/或以小写字母开头。 This is called a "backing field." 这称为“备用字段”。

The private backing field holds the actual data, the public property is just the means by which other classes can interact with that data. 私有支持字段保存实际数据,公共属性只是其他类与该数据进行交互的方式。 Inside the get and set blocks, you can place any code you want: instead of returning my backing field, I could instead put: return 5; 在get和set块内,您可以放置​​所需的任何代码:代替返回我的后备字段,我可以改为: return 5; . It's not useful, and it's poor practice, but I can. 这没有用,而且做法不好,但我可以。 Generally, the code that resides in your get and set blocks should still set or get the value; 通常,驻留在您的get和set块中的代码仍应设置或获取值。 although you might validate the input first, and/or format it first. 尽管您可能首先验证输入和/或首先对其进行格式化。 The pattern you are implementing in your sets for WPF raises an event that the property has changed. 您在WPF集合中实现的模式会引发一个事件,表明该属性已更改。 Other parts of your program are listening for that event so they know to update the UI. 程序的其他部分正在监听该事件,因此他们知道要更新UI。

So in your code, if you only change the backing field and don't raise an event that there has been a change, the UI will not update. 因此,在您的代码中,如果仅更改后备字段并且不引发发生更改的事件,则UI不会更新。 You might desire this behavior if you are performing a complex action on an object, and want to hold off performing an UI update until a complete batch of items are finished, but that's an optimization and for starters you are probably better off always accessing/setting to the Public Property. 如果您要在对象上执行复杂的操作,并且希望推迟执行UI更新,直到完成一整批项目,那么您可能会希望这种行为,但这是一种优化,对于初学者来说,最好总是访问/设置到公共财产。

暂无
暂无

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

相关问题 我们什么时候应该使用公共的,什么时候使用私有的? - When should we use public and when private? 私人阶层的公共财产 - Public property of private class 我应该使用带有公共获取方法的私有属性/字段还是直接使用公共属性进行正确封装? - Should I use a private property/field with a public getter method or directly use a public property for proper encapsulation? 用私人财产支持公共财产? - Backing a public property with a private property? 是否有性能或封装上的原因来创建要用于代替公共财产的私有变量? - Is there a performance or encapsulation reason to create a private variable to use in place of a public property? 公开嵌套私有类型的公共属性时出现“不一致的可访问性”错误 - 'Inconsistent accessibility' error when exposing a public property of a nested private type 为什么属性是公共的,而 setter 是私有的 - Why property is public and the setter is private 什么时候应该使用 public、private 或 [SerializeField]? 统一 C# - When should I use public, private, or [SerializeField]? Unity C# 当我统一使用GridLayoutGroup时,在检查器中看不到private / public字段 - private/public Field is not seen in inspector when I use GridLayoutGroup in unity 我应该在声明该属性的类中使用公共属性的私有字段吗? - Should I use a private field of a public property inside a class where I declare that property?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM