jps*_*ook 8 c# architecture asp.net
我一直在试图找出处理默认值的最佳方法.将ID值设置为0是有意义的,但如果它是金钱值或其他未初始设置的值,当您在代码中稍后遇到它时,无法判断它是否已设置或设置为0.将money值设置为null,然后您知道它尚未设置.此外,在处理数据库时,很容易知道是否需要将空值写入字段而不是尝试确定它是否应该为空.
处理这个问题的方法是什么?
Class MyModel
{
public int Id {get;set;}
public string Title {get;set;}
public DateTime CreatedDate {get;set;}
public bool IsActive {get;set;}
//CLR will automatically set these values
Public MyModel()
{
Id = 0;
Title = String.Empty;
CreatedDate = "1/1/0001";
IsActive = false;
}
}
Run Code Online (Sandbox Code Playgroud)
VS
Class MyModel
{
public int? Id {get;set;}
public string Title {get;set;}
public DateTime? CreatedDate {get;set;}
public bool? IsActive {get;set;}
//CLR will automatically set these values
Public MyModel()
{
Id = null;
Title = null;
CreatedDate = null;
IsActive = null;
}
}
Run Code Online (Sandbox Code Playgroud)
您始终可以根据您的领域混合使用方法。
\n\nstatic class ID\n{\n public const int Unassigned = -1;\n}\n\nclass MyModel\n{\n public int Id { get; private set; }\n public string Title { get; set; }\n public DateTime CreatedDate { get; set; }\n public bool IsActive { get; set; }\n public bool? IsAwesome { get; set; }\n\n Model () \n {\n // you may use "default" constants...\n Id = ID.Unassigned;\n }\n\n // you may use optional parameters or overloads\n public MyModel (string title,\n DateTime created = DateTime.Now, // default values may be concrete \n bool? isAwesome = null) // or nullable as well\n : this () // and you can chain-call constructors!\n {\n Title = title ?? "<no title>"; // you don\'t always want null to come through\n CreatedDate = created; \n IsAwesome = isAwesome; \n }\n}\n\n// Possible usages:\nvar model = new MyModel ("Hello", new DateTime (2001, 1, 1));\nvar model = new MyModel ("world", isAwesome: true);\nvar model = new MyModel (null) {\n IsActive = true\n};\nRun Code Online (Sandbox Code Playgroud)\n\n某些属性具有值可能是有意义的null,例如 \xe2\x80\x9cnot set\xe2\x80\x9d。
在您的示例中,也许模型在保存到数据库之前确实没有。Id如果是这种情况,并且无 id 模型在业务逻辑方面有意义,则 nullableId比Id = 0. 但是,如果您的应用程序从不使用无 id 模型,并且通常期望Id等于某些东西,那么编写
if (model.Id != null)\nRun Code Online (Sandbox Code Playgroud)\n\n每次你想用它做某事时。
\n\n在这种情况下,您可能应该使用Id = 0默认值。
\n你也可以引入一个常量(正如我上面所做的那样),尽管我不会推荐它用于除了 ids 之外的任何东西,并且只有在它们被其他地方的代码大量使用的情况下。
同样,一切都取决于领域。
\n您的工作是确保无法轻易创建违反业务规则的对象。
| 归档时间: |
|
| 查看次数: |
2492 次 |
| 最近记录: |