【问题标题】:Define a default string type for an attribute of a model in C#在 C# 中为模型的属性定义默认字符串类型
【发布时间】:2020-04-12 23:26:24
【问题描述】:

我有这个型号

  public class AppInfo
  {
    [Required(ErrorMessage = "Campo obrigatório")]
    public string nick { get; set; }
    [Required(ErrorMessage = "Campo obrigatório")]
    public string version { get; set; }
    public string description { get; set; }
  }

我想为nick 属性设置默认字符串类型,就像在打字稿中一样

const plant: 'Tree' | 'Flower'

在c#中有没有办法做到这一点?

【问题讨论】:

    标签: c# entity-framework model-view-controller types model


    【解决方案1】:
    public string nick { get; set; } = "Default text";
    

    如果您不手动设置,默认文本将是属性值

    【讨论】:

    • 但是我可以说这个属性只能接收两种类型的字符串,如果接收到的字符串不是类型模式,它会抛出异常吗?示例:公共字符串 nick { get;放; } = "默认文本" | “另一个文本”;
    【解决方案2】:

    在 C# 中,没有像在 TypeScript 中那样做您所描述的事情的“速记”方式。为此,您必须创建一个自定义类。如果提供的字符串不在您的“允许”列表中,它将有 1 个只读字符串属性并在构造函数中抛出异常。

    public class AppInfo
    {
      [Required(ErrorMessage = "Campo obrigatório")]
      public Plant nick { get; set; }
      [Required(ErrorMessage = "Campo obrigatório")]
      public string version { get; set; }
      public string description { get; set; }
    }
    
    public class Plant {
       private readonly string[] AllowedNames = { "Tree", "Flower" };
       public string Name { get; }
       Plant(string plant) {
          if(false == AllowedNames.Contains(plant)) {
              throw new ArgumentException($"{plant} isn't allowed.");
          }
          this.Name = plant;
       }
    
    }
    

    AppInfo 中,您将使用nick.Name 访问该属性。

    或者,您可以直接将此逻辑添加到AppInfo 构造函数。不过,如果您打算在其他实体中使用此逻辑,创建自定义类会更好。

    【讨论】:

      【解决方案3】:
          public class AppInfo
        {
          private string _nick;
          [Required(ErrorMessage = "Campo obrigatório")]
          public string nick { get{ return _nick; } set { if(value != "Tree" && value != "Flower" ){ throw new Exception("Wrong text, fool"); } this._nick = value; } }
          [Required(ErrorMessage = "Campo obrigatório")]
          public string version { get; set; }
          public string description { get; set; }
        }
      

      我更新了一点。验证属性集中的值。 如果您尝试设置 obj.nick = "notFlower"

      ,这将引发错误

      【讨论】:

        猜你喜欢
        • 2018-08-27
        • 1970-01-01
        • 1970-01-01
        • 2018-04-29
        • 1970-01-01
        • 2019-02-23
        • 1970-01-01
        • 2023-03-18
        • 2015-06-24
        相关资源
        最近更新 更多