2012-07-08 95 views
2

我有这个类:我可以创建一个构造方法的对象,当我创建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,以便我不需要执行最后三条 语句?

+0

当然......只需在构造函数中使用'this.Content'而不是'vm.Content'来构造这三个语句。 – 2012-07-08 05:17:03

回答

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:不要访问嵌套的属性,如果你没有,并告诉对象做什么但不如何(让对象本身上决定) 。

+0

谢谢。有没有一种方法可以扩展这一点,并使其成为可替代的创建ContentViewModel并在传递Content对象时拥有另一个构造函数? – Alan2 2012-07-08 05:24:05

+0

是的 - 只要添加另一个接受Content的实例就可以了。就像使用方法一样,您可以重载构造函数。 – BrokenGlass 2012-07-08 05:26:10

+0

我必须在构造函数中使用“this”这个词吗? – Alan2 2012-07-08 05:26:56

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

} 
+0

GlennFerrieLive - 你能解释第二行的功能吗?对不起,但我不明白吗?还有一种方法可以创建ContentViewModel并作为构造函数传入内容对象? – Alan2 2012-07-08 05:25:03

+0

是的。第二个像是一个“空”构造函数,它调用另一个具有一些默认参数的类构造函数。我将添加第三个构造函数到我的示例,需要'内容' – 2012-07-08 05:31:20

1

可以object initializer有用:

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

所有在一行中。

相关问题