0

我的项目中有许多对象,它们的字段在初始化时将包含匹配的值- 请参阅下面的代码片段以获取示例,特别是AddedDateTimeandModifiedDateTime属性:

User user = new User()
{
    FirstName = "Tex",
    Surname = "Murphy",
    AddedDateTime = DateTime.Now,
    ModifiedDateTime = DateTime.Now
};

设置后是否可以在 {...} 块内将的值设置ModifiedDateTime为 的值?AddedDateTime

我觉得这是不可能的,但认为值得要求确认。

4

5 回答 5

1

我不确定这是否是您的追求,但这合适吗?

var now = DateTime.Now;
User user = new User
{
     FirstName = "Tex",
     Surname = "Murphy",
     AddedDateTime = now,
     ModifiedDateTime = now
};

如果您想让它们初始化为相同的值,那么您必须设置为一个公共变量值。

于 2012-05-03T18:56:13.387 回答
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; }
  }
}
于 2012-05-03T18:57:06.950 回答
0
User user = new User
            {
                FirstName = "Tex",
                Surname = "Murphy",
                AddedDateTime = DateTime.Now < Something? DateTime.Now : SomeOtherValue,
                ModifiedDateTime = DateTime.Now < Something? DateTime.Now : SomeOtherValue
            };
于 2012-05-03T18:47:53.760 回答
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;
};
于 2012-05-03T18:51:30.540 回答
0

您可以将逻辑放入 AdditionalDateTime 的设置器中,检查 ModifiedDateTime 上的最小值并进行相应设置。例如

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
};
于 2012-05-03T18:54:41.287 回答