简体   繁体   English

在C#中是否可以使用相同名称的公共getter和私有setter?

[英]Is a public getter and a private setter with same name possible in C#?

How can I create a public getter and a private setter for a property? 如何为财产创建公共获取者和私有设定者? Is the following correct? 以下正确吗?

public String Password
{
    set { this._password = value; }
}

private String Password
{
    get { return this._password; }
}

Yes it is possible, even with auto properties. 是的,即使具有自动属性,也是可能的。 I often use: 我经常使用:

public int MyProperty { get; private set; }

Yes, as of C# 2.0, you can specify different access levels for the getter and the setter of a property. 是的,从C#2.0开始,您可以为属性的getter和setter指定不同的访问级别。

But you have the syntax wrong: you should declare them as part of the same property. 但是语法有误:您应该将它们声明为同一属性的一部分。 Just mark the one you want to restrict with private . 只需用private标记要限制的那个即可。 For example: 例如:

public String Password
{
    private get { return this._password; }
    set { this._password = value; }
}
public String Password
{
    private set { this._password = value; }
    get { return this._password; }
}

or you can use an auto-implemented property: 或者您可以使用自动实现的属性:

public String Password { get; private set; }
public String Password
{
    private set { this._password = value; }
    get { return this._password; }
}

MSDN: MSDN:

The get and set methods are generally no different from other methods. get和set方法通常与其他方法没有什么不同。 They can perform any program logic, throw exceptions, be overridden, and be declared with any modifiers allowed by the programming language. 它们可以执行任何程序逻辑,引发异常,被覆盖并使用编程语言允许的任何修饰符进行声明。

Edit: MSDN quote is just to clarify why geter and setter can have different access mdofiers, Good point raised by @Cody Gray: 编辑:MSDN报价只是为了阐明为什么geter和setter可以具有不同的访问mdofiers,@ Cody Gray提出的好处是:

Yes, properties can perform program logic and throw exceptions. 是的,属性可以执行程序逻辑并引发异常。 But they shouldn't. 但是他们不应该。 Properties are intended to be very lightweight methods, comparable to accessing a field. 属性是一种非常轻量级的方法,可与访问字段进行比较。 The programmer should expect to be able to use them as they would a field without any noticeable performance implications. 程序员应该期望能够像使用字段一样使用它们而不会引起任何明显的性能影响。 So too much heavy program logic is strongly discouraged. 因此,强烈建议不要过多使用繁琐的程序逻辑。 And while setters can throw exceptions if necessary, getters should almost never throw exceptions 尽管setter可以在必要时抛出异常,但getter几乎绝不应抛出异常

public string Password { get; private set; }

To gain an 'Excavator' badge, and to make the answer up to date - readonly fields encapsulated by a get-only property 要获得“挖掘机”徽章并及时回答问题,请使用get-only属性封装的只读字段

private readonly int myVal;
public int MyVal get { return myVal; }

may be now (as of C# 6.0) shortened to 可能现在(从C#6.0开始)缩短为

public int MyVal { get; }

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM