首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >从构造函数调用方法

从构造函数调用方法
EN

Stack Overflow用户
提问于 2017-12-20 04:55:15
回答 3查看 59关注 0票数 0

我在构造函数中调用一个方法,如below.Is,这是根据某些validations.Please建议设置属性的正确方法。

代码语言:javascript
运行
复制
    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;
          }
      }
  }
EN

回答 3

Stack Overflow用户

回答已采纳

发布于 2017-12-20 07:07:17

简单地试试这个

代码语言:javascript
运行
复制
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方式。

代码语言:javascript
运行
复制
using System.ComponentModel.DataAnnotations;

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

Stack Overflow用户

发布于 2017-12-20 05:09:34

我认为你的设计应该如下所示,

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

并从客户端(使用者)决定您需要哪个实例并构造它。

代码语言:javascript
运行
复制
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;
    }
}
票数 2
EN

Stack Overflow用户

发布于 2017-12-20 06:37:31

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

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/47899022

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档