lex*_*eme 4 c# validation inheritance interface automatic-properties
我建议我有一个接口并从中继承类,
internal interface IPersonInfo
{
String FirstName { get; set; }
String LastName { get; set; }
}
internal interface IRecruitmentInfo
{
DateTime RecruitmentDate { get; set; }
}
public abstract class Collaborator : IPersonInfo, IRecruitmentInfo
{
public DateTime RecruitmentDate
{
get;
set;
}
public String FirstName
{
get;
set;
}
public String LastName
{
get;
set;
}
public abstract Decimal Salary
{
get;
}
}
Run Code Online (Sandbox Code Playgroud)
那么如何验证协作者类中的字符串?是否可以实现内部属性?
是的,但不使用自动属性.您需要使用支持字段手动实现属性:
private string firstName;
public String FirstName
{
get
{
return firstName;
}
set
{
// validate the input
if (string.IsNullOrEmpty(value))
{
// throw exception, or do whatever
}
firstName = value;
}
}
Run Code Online (Sandbox Code Playgroud)
像这样的东西...
private string _firstName;
public string FirstName
{
get
{
return _firstName;
}
set
{
if (value != "Bob")
throw new ArgumentException("Only Bobs are allowed here!");
_firstName = value;
}
}
Run Code Online (Sandbox Code Playgroud)
基本上,您用于属性的是语法糖版本。在编译时,他们创建一个私有成员变量并连接属性以使用该变量,就像我在这里手动执行的那样。这样做的确切原因是,如果您想添加逻辑,您可以将其转换为手动操作,就像我在这里所做的那样,而不会破坏接口的实现。