从构造函数调用方法

问题描述 投票:0回答:3

我在我的构造函数中调用一个方法,如下所示。这是根据一些验证设置属性的正确方法。请建议。

    public class Asset
    {
      public Asset(string id)
      {
        SetStorageId(id);
      }

      public string AssetId { get; set; }

      public string UtilId { get; set; }

      public string MappingId { get; set; }

      public bool IsActive { get; set; }

      private void SetStorageId(string id)
      {
          if (Regex.Match(id, "^[A-Z][a-zA-Z]*$").Success)
          {
              AssetId = id;
          }
          else
          {
            UtilId = id;
          }
      }
  }
c# asp.net c#-4.0
3个回答
1
投票

试试吧

public class Asset
{
    private string id;


    public string AssetId { get; set; }
    public string UtilId { get; set; }
    public string Id
    {
        set
        {
            if (Regex.Match(value, "^[A-Z][a-zA-Z]*$").Success)
            {
                this.id = value;
            }
            else
            {
                UtilId = value;
            }
        }
        get
        {
            return id;
        }
    }
}

在c#中创建属性时,会在编译时为该属性创建一个私有变量。当您尝试在上面的代码中设置Id属性时,您传递的ID将转到value关键字,您可以对value关键字执行验证并相应地设置您的属性。无需使用set方法,构造函数或派生类使代码复杂化

或者您甚至可以使用数据注释,这是一种更优雅的方式https://msdn.microsoft.com/en-us/library/system.componentmodel.dataannotations.validationattribute.aspx#Properties

using System.ComponentModel.DataAnnotations;

public class Asset
{
    [RegularExpression("^[A-Z][a-zA-Z]*$")]
    public string Id { get; set; }
}

2
投票

在我看来,你的设计应如下所示,

您应该将公共项抽象到基类并创建继承此类的特定类,

并从客户(消费者)决定您需要哪个实例并构建它

public class AssetBase
{
    public string MappingId { get; set; }

    public bool IsActive { get; set; }        
}

public class Asset : AssetBase
{
    public string AssetId { get; set; }
}

public class Util : AssetBase
{
    public string UtilId { get; set; }
}

static void Main(string[] args)
{
    string id = Console.ReadLine();

    if (Regex.Match(id, "^[A-Z][a-zA-Z]*$").Success)
    {
        Asset asset = new Asset();
        asset.AssetId = id;
    }
    else
    {
        Util util = new Util();
        util.UtilId = id;
    }
}

0
投票

这没错。它可能会变得有点混乱。也许你可以通过将SetStorageId的身体移动到构造函数来使它更清晰。相对于项目中的其他代码,也许没有必要使子类化复杂化。

© www.soinside.com 2019 - 2024. All rights reserved.