将当前日期分配给MVC中的属性 [英] Assign current date to a property in MVC
本文介绍了将当前日期分配给MVC中的属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在为用户创建一个模型,并且我希望将加入的属性设置为Now().这是我的代码:
I am creating a model for users and I want that property joined was set to Now(). Here's my code:
[DefaultValue(DateTime.Now)]
public DateTime joined {get; set;}
我收到错误消息:
属性参数必须是属性参数类型的常量表达式,typeof表达式或数组创建表达式.
An attribute argument must be a constant expression, typeof expression or array creation expression of an attribute parameter type.
我做错了什么?而做我想要的最好的方法是什么?
What am I doing wrong? And what's the best way to do what I want?
推荐答案
DateTime.Now
不是常量,而是在运行时计算的属性,这就是为什么您不能按照建议执行的原因.
DateTime.Now
is not a constant, but a property that's computed at runtime, which is why you can't do what you're suggesting.
您可以使用以下任一方法来完成您的建议:
You can do what you're proposing with either:
public class MyClass {
public DateTime joined { get; set; }
public MyClass() {
joined = DateTime.Now;
}
}
或者:
public class MyClass {
private DateTime _joined = DateTime.Now;
public DateTime joined { get { return _joined; } set { _joined = value; } }
}
这篇关于将当前日期分配给MVC中的属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文