c# - 在 C# 中创建新类时的快捷方式

标签 c#

是否有可能以任何方式清理以下代码?

这是我在代码中使用的:

var _index = new IndexViewModel();
_index.PageMeta = new PageMeta();
_index.Que = new Q();
_Index.Test = new T();

这是我的类定义:

public class IndexViewModel {
   public PageMeta PageMeta { get; set; }
   public T Test { get; set; }
   public Q Que { get; set; }
}

我试图记住在声明新类时是否有捷径。我可以在 IndexViewModel 的构造函数中添加一些东西吗?

最佳答案

好吧,你可以使用一个对象初始化器:

var _index = new IndexViewModel 
{
    PageMeta = new PageMeta(),
    Que = new Q(),
    Test = new T()
};

这可能不是什么捷径,但确实为您节省了一些重复代码。

编辑以澄清评论中的问题

public class IndexViewModel {

   // The default constructor now initializes de values:
   public IndexViewModel() 
   {
       PageMeta = new PageMeta();
       Q = new Q();
       T = new T();
   }

   public PageMeta PageMeta { get; set; }
   public T Test { get; set; }
   public Q Que { get; set; }
}

如果将初始化添加到构造函数中,则不再需要使用对象初始化器:

var _index = new IndexViewModel(); //<- initialized by its own constructor

关于c# - 在 C# 中创建新类时的快捷方式,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6530870/

相关文章:

C# - 返回泛型数组类型

c# - 如何填充类中的列表

c# - 如何调用 window.alert ("message");来自 C#?

c# - 我应该如何存储用户指定的一组文件?

c# - 将对象序列化为数组

c# - 如何遍历 dacpac

c# - 如何在 C# 中将此功能编写为通用扩展方法?

c# - Entity Framework 不为表或过程生成类

c# - Windows 服务 : Get processes for all users, 包括 MainWindowHandle

c# - C# Windows 窗体中的 VLC 视频播放器不播放 .flv 网络文件