当我们在编写代码时会经常遇到初始化一个的类,需要通过构造函数进行对象初始化。那么这个时候我们可能会需要逐个去手动写,这样的工作即重复又无趣。如果是在项目非常紧急的情况下还有大量的字段需要与入参一一对应起来简直太要命了。大致情况如下:.
public class Configinfo : Entity
{
public Configinfo() { }
public Configinfo(int appType, string appName, string appSecretKey, string clientVersion, string updateUrl, string updateLogUrl, string installPath, string mainUpdateUrl, string mainAppName)
{
AppType = appType;
AppName = appName ?? throw new ArgumentNullException(nameof(appName));
AppSecretKey = appSecretKey ?? throw new ArgumentNullException(nameof(appSecretKey));
ClientVersion = clientVersion ?? throw new ArgumentNullException(nameof(clientVersion));
UpdateUrl = updateUrl ?? throw new ArgumentNullException(nameof(updateUrl));
UpdateLogUrl = updateLogUrl ?? throw new ArgumentNullException(nameof(updateLogUrl));
InstallPath = installPath ?? throw new ArgumentNullException(nameof(installPath));
MainUpdateUrl = mainUpdateUrl ?? throw new ArgumentNullException(nameof(mainUpdateUrl));
MainAppName = mainAppName ?? throw new ArgumentNullException(nameof(mainAppName));
}
/// <summary>
/// 1:ClientApp 2:UpdateApp
/// </summary>
public int AppType { get; set; }
/// <summary>
/// Need to start the name of the app.
/// </summary>
public string AppName { get; set; }
/// <summary>
/// application key
/// </summary>
public string AppSecretKey { get; set; }
/// <summary>
/// Client current version.
/// </summary>
public string ClientVersion { get; set; }
/// <summary>
/// Update check api address.
/// </summary>
public string UpdateUrl { get; set; }
/// <summary>
/// Update log web address.
/// </summary>
public string UpdateLogUrl { get; set; }
/// <summary>
/// installation path (for update file logic).
/// </summary>
public string InstallPath { get; set; }
/// <summary>
/// Update check api address.
/// </summary>
public string MainUpdateUrl { get; set; }
public string MainAppName { get; set; }
}
看起来是不是非常头疼,那么如何解决这个问题呢?可以通过VisualStudio帮助开发者进行这重复的工作。
-
空白处点击一下,会出现一个小工具图标
-
点击小工具,选择生成构造函数。
-
选择需要作为构造函数的参数
-
生成代码如下
public Configinfo(int appType, string appName, string appSecretKey, string clientVersion, string updateUrl, string updateLogUrl, string installPath, string mainUpdateUrl, string mainAppName)
{
AppType = appType;
AppName = appName ?? throw new ArgumentNullException(nameof(appName));
AppSecretKey = appSecretKey ?? throw new ArgumentNullException(nameof(appSecretKey));
ClientVersion = clientVersion ?? throw new ArgumentNullException(nameof(clientVersion));
UpdateUrl = updateUrl ?? throw new ArgumentNullException(nameof(updateUrl));
UpdateLogUrl = updateLogUrl ?? throw new ArgumentNullException(nameof(updateLogUrl));
InstallPath = installPath ?? throw new ArgumentNullException(nameof(installPath));
MainUpdateUrl = mainUpdateUrl ?? throw new ArgumentNullException(nameof(mainUpdateUrl));
MainAppName = mainAppName ?? throw new ArgumentNullException(nameof(mainAppName));
}