从构造函数调用方法

时间:2017-12-20 04:55:16

标签: c# asp.net c#-4.0

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

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

3 个答案:

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

答案 1 :(得分: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 :(得分:0)

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