2

我有这堂课:

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 以便我不需要执行最后三个语句?

4

3 回答 3

2

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

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 和得墨忒耳法则:如果不需要,不要访问嵌套属性,并告诉对象做什么而不是如何做(让对象自己决定)。

于 2012-07-08T05:19:12.067 回答
1

可能object initializer有用:

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

都在一条线上。

于 2012-07-08T05:22:56.853 回答
1

是的,像这样:

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; } 

} 
于 2012-07-08T05:18:44.227 回答