[英]C#: Can you mix function access modifiers when using getter/setter shortand?
Looking at a WCF tutorial, there is a class with private variable declarations and public getters and setters for those declarations. 在WCF教程中,有一个带有私有变量声明以及这些声明的公共获取器和设置器的类。 Is it possible to have this same combination of modifiers (ie private vars with a publicly exposed accessors) using the shortand
get
and set
declarations? 是否可以使用shortand
get
和set
声明具有相同的修饰符组合(即具有公开访问器的私有var)?
For example: 例如:
public class MyClass{
private int someNumber;
public int someNumber {
get {return someNumber;}
set {someNumber = value;}
}
}
This question here suggests you can mix modifiers like this: 这个问题在这里建议您可以混合使用如下修饰符:
public class MyClass{
private int someNumber {public get; public set;};
}
Is that correct? 那是对的吗? (Also, in this specific example I can't see the point of marking
int someNumber
as a private variable. Am I right that this would be pointless?) (此外,在这个特定示例中,我看不到将
int someNumber
标记为私有变量的意思。我对,这毫无意义吗?)
You can but the inner property methods must be more restrictive than the outside property itself. 您可以,但是内部属性方法必须比外部属性本身更具限制性。
public int someNumber { get; private set; }
This is how you make an externally read-only property. 这就是您使外部只读属性的方式。
This doesn't work (the compiler will complain) and does not make a lot of sense: 这是行不通的(编译器会抱怨)并且没有任何意义:
private int someNumber { get; public set; }
You can have different visibility level but you should always go from the more restrictive to the more open. 您可以具有不同的可见性级别,但应始终从限制更严格到开放程度更高。
For instance you can have : 例如,您可以拥有:
public string MyProperty { get; internal set; }
But you can't have : 但您不能拥有:
private string MyProperty { public get; set; }
As the public access modifier of the getter is more visible than the private access modifier on the property. 因为吸气剂的公共访问修饰符比属性上的私有访问修饰符更可见。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.