在 ViewModel 中使用 setter 使用另一个 属性
Using setter in ViewModel using another property
我的应用程序中有以下 ViewModel
并且有两个 BirthDate
属性(有/没有时间)。在没有 body 的情况下使用 set { }
时,我遇到了 "Not using the value means that the accessor ignores the caller's intent which could cause unexpected results at runtime."。然后我添加了一个私有 属性 并将更新集设置为 set { birthDateWithTime = value; }
。不过这次birthDateWithTime
private 属性 看不到用。下面的实现有没有错误?我想分别使用 属性 并且不想在 JavaScript 或代码中进行转换。
public class DemoViewModel
{
public int Id { get; set; }
public DateTime BirthDate { get; set; }
private string birthDateWithTime;
public string BirthDateWithTime {
get { return BirthDate.ToString("dd/MM/yyyy - HH:mm"); }
set { birthDateWithTime = value; }
}
}
如果仅依赖于 BirthDate
,请尝试此操作
public string BirthDateWithTime
{
get
{
return BirthDate.ToString("dd/MM/yyyy - HH:mm");
}
}
或者只使用 body-属性 样式。
public string BirthDateWithTime => BirthDate.ToString("dd/MM/yyyy - HH:mm");
@Gabriel Llorico 回答正确。或者你可以试试另一个。
private DateTime _birthDate;
public DateTime BirthDate{
get{
return _birthDate;
}
set{
this._birthDate = value;
this.BirthDateWithTime = this._birthDate.ToString("dd/MM/yyyy - HH:mm");
}
}
public string BirthDateWithTime{get;set;}
如果您需要设置BirthDateWithTime,只需在BirthDate 属性中设置,这样两者都会更新。
我的应用程序中有以下 ViewModel
并且有两个 BirthDate
属性(有/没有时间)。在没有 body 的情况下使用 set { }
时,我遇到了 "Not using the value means that the accessor ignores the caller's intent which could cause unexpected results at runtime."。然后我添加了一个私有 属性 并将更新集设置为 set { birthDateWithTime = value; }
。不过这次birthDateWithTime
private 属性 看不到用。下面的实现有没有错误?我想分别使用 属性 并且不想在 JavaScript 或代码中进行转换。
public class DemoViewModel
{
public int Id { get; set; }
public DateTime BirthDate { get; set; }
private string birthDateWithTime;
public string BirthDateWithTime {
get { return BirthDate.ToString("dd/MM/yyyy - HH:mm"); }
set { birthDateWithTime = value; }
}
}
如果仅依赖于 BirthDate
public string BirthDateWithTime
{
get
{
return BirthDate.ToString("dd/MM/yyyy - HH:mm");
}
}
或者只使用 body-属性 样式。
public string BirthDateWithTime => BirthDate.ToString("dd/MM/yyyy - HH:mm");
@Gabriel Llorico 回答正确。或者你可以试试另一个。
private DateTime _birthDate;
public DateTime BirthDate{
get{
return _birthDate;
}
set{
this._birthDate = value;
this.BirthDateWithTime = this._birthDate.ToString("dd/MM/yyyy - HH:mm");
}
}
public string BirthDateWithTime{get;set;}
如果您需要设置BirthDateWithTime,只需在BirthDate 属性中设置,这样两者都会更新。