开发者

C# property definition

For C# properties, I can do this:

public class Employee{

 public string Name { get; private set; }

 public Employee(string name){
  Name = name;
 }

}

which means that the Name property can be set within the class Employee & can be read publicly.

But, if I want to restrict the set to only within the constructors of the Employee class, I need to do:

public class Employee{
 public readonly string Name = String.Empty;
 public Employee(string name){
  Name = name;
 }
}

But, for this case, I had to change the property to a field.

Is there any reason this is not possible/allowed in C#:

public class Employee{
 public string Name { get; private readonly set; }
 public Employee(string name){
  Name = name;
 }
}

IMO this will allow us to have properties which can be set only in the construct开发者_Go百科or & does not require us to change properties to fields...

Thanks!


Use

private readonly string name = Empty.String;
public string Name { get { return name; } }


What's wrong with:

public class Employee
{

 private string nameField;
 public string Name 
 { 
  get
  {
    return this.nameField;
  }
 }
 public Employee(string name)
 {
   this.nameField = name;
 }


readonly applies to variables and not to methods. set is converted into a method by the compiler, and therefore the readonly attribute makes no sense.

In order to accomplish what you want you need.

public class Employee
{
   private readonly string _name;

   public string Name
   { 
      get
      {
         return _name;
      }
   }

   public Employee(string name)
   {
      _name = name;
   }
}


If you're concerned with only setting the properties within the constructor of the class that you're currently within, just make it a property with a private setter and don't set it in the class.. it's not like you don't have control over that situation.

$0.02


You can have

public class Employee{
 public string Name { get; private set; }
 public Employee(string name){
  Name = name;
 }
}

Which will make a readonly public property. If you think about it, having a private readonly setter on a public property doesn't really make sense because you're wanting the setter to be readonly which is a method, not a variable.

If you were to make the setter readonly, essentially what you're doing is denying any access whatsoever to setting the value of the property. This is why you need the backing field.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜