我的项目中有许多对象,这些对象的字段在初始化时包含匹配值 - 请参阅下面的代码段,例如,
特别是AddedDateTime
和ModifiedDateTime
属性:
User user = new User()
{
FirstName = "Tex",
Surname = "Murphy",
AddedDateTime = DateTime.Now,
ModifiedDateTime = DateTime.Now
};
一旦设置了{...}块,是否可以将ModifiedDateTime
的值设置为AddedDateTime
的值?
我觉得这是不可能的,但认为值得请求确认。
答案 0 :(得分:1)
我不确定这是否适合您,但这是否合适?
var now = DateTime.Now;
User user = new User
{
FirstName = "Tex",
Surname = "Murphy",
AddedDateTime = now,
ModifiedDateTime = now
};
如果要将它们初始化为相同的值,则必须设置为公共变量值。
答案 1 :(得分:1)
您可以将此逻辑放入属性的实现中:
public class User{
private DateTime added;
private DateTime? modified;
string FirstName {get;set;}
string SurName {get;set;}
DateTime AddedDateTime {
get { return added; }
set { added = value;
modified = modified ?? value;
}
}
DateTime? ModifiedDateTime {
get { return modified }
set { modified = value; }
}
}
答案 2 :(得分:0)
User user = new User
{
FirstName = "Tex",
Surname = "Murphy",
AddedDateTime = DateTime.Now < Something? DateTime.Now : SomeOtherValue,
ModifiedDateTime = DateTime.Now < Something? DateTime.Now : SomeOtherValue
};
答案 3 :(得分:0)
如评论中所述,您可以构建仅包含所需数据的构造函数,即:
public User(string firstName, string sirname)
{
FirstName = firstName,
Surname = sirname,
AddedDateTime = DateTime.Now,
ModifiedDateTime = DateTime.Now
};
您还可以使用辅助方法来创建类的实例。它们可以在课堂内或不在课堂上(如果你不能控制课程本身,这很有用)
public static User CreateUser(string firstName, string sirname)
{
User newUser = new User();
newUser.FirstName = firstName,
newUser.Surname = sirname,
newUser.AddedDateTime = DateTime.Now,
newUser.ModifiedDateTime = DateTime.Now
return newUser;
};
你也可能有类似的东西:
public static User CreateUser(string firstName, string sirname, string otherdata)
{
User newUser = new User();
newUser.FirstName = firstName,
newUser.Surname = sirname,
newUser.AddedDateTime = DateTime.Now,
newUser.ModifiedDateTime = DateTime.Now,
newUser.SomeField = otherdata,
newUser.SomeOtherField = otherdata
return newUser;
};
答案 4 :(得分:0)
您可以将逻辑放入AddedDateTime的setter中,该setter在ModifiedDateTime上检查最小值并进行相应设置。 e.g。
public DateTime ModifiedDateTime { get; set; }
private DateTime _addedDateTime;
public DateTime AddedDateTime {
get { return _addedDateTime; }
set
{
if (ModifiedDateTime == DateTime.MinValue)
{
ModifiedDateTime = _addedDateTime = value;
};
}
}
...
var test = new Test
{
AddedDateTime = DateTime.Now
};