繁体   English   中英

我可以在C#中创建类时在构造函数中创建对象吗

[英]Can I create an object in a constructor when I create a class in C#

我有这个课:

public class ContentViewModel
{
    public Content Content { get; set; }
    public bool UseRowKey { 
        get {
            return Content.PartitionKey.Substring(2, 2) == "05" ||
               Content.PartitionKey.Substring(2, 2) == "06";
        }
    }
    public string TempRowKey { get; set; }

}

我现在正在这样做:

        var vm = new ContentViewModel();
        vm.Content = new Content(pk);
        vm.Content.PartitionKey = pk;
        vm.Content.Created = DateTime.Now;

有什么方法可以更改ContentViewModel,而不必执行最后三个语句?

为什么不将参数传递给构造函数?

public class ContentViewModel
{
    public ContentViewModel(SomeType pk)
    {
        Content = new Content(pk); //use pk in the Content constructor to set other params
    }  
    public Content Content { get; set; }
    public bool UseRowKey { 
        get {
            return Content.PartitionKey.Substring(2, 2) == "05" ||
               Content.PartitionKey.Substring(2, 2) == "06";
        }
    }
    public string TempRowKey { get; set; }
}

一般认为OOP和得墨忒耳定律 :不要访问嵌套的属性,如果你没有,告诉对象做什么而不是如何 (让自己对决定的对象)。

是的,像这样:

public class ContentViewModel 
{ 
    public ContentViewModel(Content c) 
    {
        if (c == null) throw new ArgumentNullException("Cannot create Content VM with null content.");
        this.Content = c;
    }
    public ContentViewModel(object pk) : this(Guid.NewGuid()) {}
    public ContentViewModel(object pk)
    {
        this.Content = new Content(pk); 
        this.Content.PartitionKey = pk; 
        this.Content.Created = DateTime.Now; 
    }

    public Content Content { get; set; } 
    public bool UseRowKey {  
        get { 
            return Content.PartitionKey.Substring(2, 2) == "05" || 
               Content.PartitionKey.Substring(2, 2) == "06"; 
        } 
    } 
    public string TempRowKey { get; set; } 

} 

object initializer可能有用:

var vm = new ContentViewModel {Content = new Content {PartitionKey = pk, Created = DateTime.Now}};

一站式

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM