class Anything
{
List<string> PPP = new List<string>()
{
"table",
"chair",
"spoon",
"bread"
};
string name;
}
name
必须是PPP
。
name = "bed" //must be an error.
我应该如何为name
写一个属性?
课程Anything
的建议者?
例如,我每次都可以使用foreach查看值。但我想知道还有另外一种方法吗? PPP很少可以增值。所以我不使用Enum。 这只是我计划的一小部分。我是OOP的初学者。 我不使用数据库或表单。我通过oop在控制台工作。
答案 0 :(得分:1)
您可以在set
的{{1}}访问者中控制它:
name
如果效果有问题,请将class Anything
{
public Anything(string name)
{
Name = name; // this will call the `set` accessor
}
List<string> PPP = new List<string>()
{
"table",
"chair",
"spoon",
"bread"
};
private string name;
public string Name
{
get {return name;}
set
{
if (!PPP.Contains(value))
throw new ArgumentException("value");
name = value;
}
}
}
更改为List<string>
。
答案 1 :(得分:0)
如何为这个类编写构造函数?
class Anything
{
public Anything(string name)
{
if(ppp.Contains(name))
this.name = name;
else
throw new ArgumentException("Name invalid");
}
private List<string> ppp = new List<string>()
{
"table",
"chair",
"spoon",
"bread"
};
private string name;
}
您可能已经注意到我已经为您的代码应用了一些C#约定:
PPP
更改为ppp
。惯例是私有字段为lowerCamelCase。答案 2 :(得分:0)
public class Anything
{
private List<string> PPP = new List<string>()
{
"table",
"chair",
"spoon",
"bread"
};
private string _name;
// Public property to have access for reading it outside the class but
// with private setter to set it only inside class
public string Name {
get { return _name; }
private set {
// Use linq to verify name
if(PPP.Contains(value))
{
_name = value;
}
else
{
string message = string.Format("{0} is not acceptable value!", value)
throw new InvalidOperationException(message);
}
}
};
// Constructor
public Anything(string name)
{
this.Name = name;
}
}