在C#中创建类时,是否可以在构造函数中创建对象?

时间:2012-07-08 05:12:30

标签: 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,这样我就不需要做最后三个了 语句?

3 个答案:

答案 0 :(得分: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和Law of Demeter:如果你不必访问嵌套属性并告诉对象要做什么而不是如何 >(让对象自己决定)。

答案 1 :(得分: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; } 

} 

答案 2 :(得分:1)

可能object initializer有用:

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

全部在一行。