简体   繁体   English

c# 修改 getter/setter 但保留简短形式

[英]c# modify getter/setter but keep the short form

I need to do a minor check in C# setter - check if property is an empty string.我需要在 C# setter 中做一个小检查 - 检查属性是否为空字符串。 Right now I ended up with structure like that:现在我最终得到了这样的结构:

        private string property;
        public string Property
        {
           get
           {
              return property;
           }
           set
           {
              if (value.IsNotEmpty())
              {
                   property = value;
              }
           }
        }

Instead of代替

public string Property { get; set; }

6 lines instead of 1. Is there a way to insert the logic, but keep it condensed and elegant? 6 行而不是 1 行。有没有办法插入逻辑,但保持简洁和优雅?

No

Auto-properties (or the "short form") can have access modifiers, but no logic.自动属性(或“简短形式”)可以有访问修饰符,但没有逻辑。 You are stuck with the code you have.你被你拥有的代码困住了。

One thing you could do is to encapsulate your string in an object that allows for an implicit cast from string (and to string), and checks IsNotEmpty before assigning to a underlying value.可以做的一件事是将您的string封装在一个对象中,该对象允许从字符串(和字符串)进行隐式转换,并在分配给基础值之前检查IsNotEmpty Also not the most elegant solution, but it would probably allow you to keep the syntactic sugar.也不是最优雅的解决方案,但它可能会让您保留语法糖。

No, there is no syntax sugar for such cases (at least up to C# 5.0 - current for 2014).不,这种情况没有语法糖(至少到 C# 5.0 - 2014 年的当前版本)。

You can format them differently and use ?: instead of if if it looks nice enough to you:您可以以不同的方式格式化它们并使用?:而不是if如果它看起来对您来说足够好:

    public string Property
    {
       get { return property; }
       set { property = value.IsNotEmpty() ? value: property;}
    }

It's not exactly what you ask, but perhaps you can use DataAnnotations, for not allowing an empty string.这不完全是你问的,但也许你可以使用 DataAnnotations,因为不允许空字符串。 Something like this, in this case a validation exception is raised if the property is null, an empty string (""), or contains only white-space characters.像这样,在这种情况下,如果属性为 null、空字符串 ("") 或仅包含空白字符,则会引发验证异常。

  [Required]
  public string Property { get; set; }

You can always make it like this.你总是可以做到这一点。

It does compact it but offers no performance boost doing it this way.它确实紧凑,但不会以这种方式提供性能提升。

    private string property;
    public string Property { get { return property; } set { if (value.IsNotEmpty()) property = value; } }

As of C# 7, properties support arrow syntax, making the following possible:从 C# 7 开始,属性支持箭头语法,从而实现以下功能:

private string property;
public string Property
{
    get => property;
    set => property = value.IsNotEmpty() ? value : property;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM