Specifying just a setter on a set/getter
I'm using getters and setters for creating an instance of a class.
Is it possible to adjust the value being set without having to have a private variable, and do it on the type directly?
For example, if my class is:
public class Cat()
{
public String Age{get; set; }
}
and I want to instantiate it doing:
new Cat({Age: "3"});
Now, if I have a function called ConvertToHumanYears that I want to call before it is being stored, I would imagine something like this is the right way:
public class Cat()
{
public String Age{get; set{ value = ConvertToHumanYears(value); }
}
But the above (and many dirivatives of it) seem to return errors. Is it possible to do something similar without having to have an additional pri开发者_Python百科vate variable I set and get?
You cannot use auto property for getter and have a definition for setter.
it's either
public class Cat()
{
   public String Age{get; set; }
}
or
public class Cat()
{
  private String _age;
    public String Age{
      get{
          return _age;
      }
      set{
           _age = ConvertToHumanYears(value); 
      }
    }
  }
}
How about this?
public class Cat
{
    public string Age { get; private set; }
}
You have to have the setter, but it's callable only inside the class itself.
You can then create a constructor that allows setting the value:
public Cat(string age)
{
    Age = age;
}
or
public Cat(string age)
{
    Age = ConvetToHumanYears(age);
}
In this case, it's no use but I had a similar problem where I just wanted set to be private and get to be public, instead of specifying the setter I marked it private. I didn't now we could do that.
public String Age{get; private set; }
Sometimes the more obvious it is, the more difficult it is to find. Hope this helps someone !
 
         加载中,请稍侯......
 加载中,请稍侯......
      
精彩评论