简体   繁体   English

我可以为 C# 自动实现的属性(也称为自动支持字段)定义自定义 getter 吗?

[英]Can I define a custom getter for a C# auto-implemented property (a.k.a. auto backing field)?

Note: I know how to accomplish this without using auto-implemented properties, but I'm wondering if C# has a built-in way to do this.注意:我知道如何在使用自动实现的属性的情况下完成此操作,但我想知道 C# 是否有内置方法来执行此操作。

Let's say I have this simple example of an auto-implemented property (aka auto backing field):假设我有一个自动实现的属性(又名自动支持字段)的简单示例:

public class MyClass
{
    public MyClass(){}
    public string MyString { get; private set; }
}

Now, I would like to return a custom exception in the getter if the auto backing field is null:现在,如果自动支持字段为空,我想在 getter 中返回一个自定义异常:

public class MyClass
{
    public MyClass(){}
    public string MyString
    {
        get
        {
            return [backing field] ?? throw new Exception("MyString is null");
        }
        private set;
    } = null;
}

Do newer C# versions support something like this?较新的 C# 版本是否支持这样的东西? Perhaps there is some syntactic sugar that I can use in place of [backing field] to access the backing field that is automatically created by the compiler?也许有一些语法糖可以用来代替[backing field]来访问编译器自动创建的支持字段?

Note on putting an exception in the getter: I know it shouldn't be a habit.关于在 getter 中放置异常的注意事项:我知道这不应该是一种习惯。 But Microsoft does it occasionally;但微软偶尔会这样做。 for example, the property HttpContext.Request.Form will throw an exception if the request is not of the proper content-type.例如,如果请求的内容类型不正确,属性HttpContext.Request.Form将引发异常。

No, you can not access to backing field in this way.不,您不能以这种方式访问​​支持字段。

You must define backing field and validate it.您必须定义支持字段并对其进行验证。

public class MyClass
{
    public MyClass(){}
    private string? _myString
    public string MyString
    {
        get
        {
            return _myString ?? throw new Exception("MyString is null");
        }
        private set => _myString  = value;
    } = null;
}

As Fred said, its better to validate it outside of property.正如弗雷德所说,最好在财产之外验证它。

I'm surprised noone mentioned the field keyword, it is exactly what you are asking for (what you would use instead of [backing field] in your example).我很惊讶没有人提到field关键字,这正是您所要求的(在您的示例中您将使用什么而不是[backing field] )。 It was supposed to be shipped with C# 10. It seems it is going to be shipped with C# 11 instead (?)它应该与 C# 10 一起提供。它似乎将与 C# 11 一起提供(?)

Search for Field Keyword here . 在此处搜索字段关键字

Put validation in the setter and/or ensure that the constructor sets a valid/non-null default value.将验证放入 setter 和/或确保构造函数设置有效/非空默认值。

Or make the property nullable to hint to the customer that they have to account for a null value possibility.或者使属性可以为空,以向客户暗示他们必须考虑空值的可能性。

Alternatively (but less optimally for multiple reasons), make the property private and add a method for accessing it.或者(但由于多种原因不太理想),将属性设为私有并添加访问它的方法。

Strongly advise against a property get directly throwing an exception.强烈建议不要让一个属性直接抛出异常。 You or the consumer will dislike the results at some point.您或消费者在某些时候会不喜欢结果。

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

相关问题 引用自动实现属性的支持字段 - Reference to the backing field of auto-implemented property 如何访问自动实现的属性的支持变量? - How can I access the backing variable of an auto-implemented property? Mono.Cecil自动实现属性访问后备字段 - Mono.Cecil auto-implemented property accessing backing field 在C#中,我可以为自动实现的属性访问器创建委托实例吗? - In C# can I create a delegate instance to an auto-implemented property accessor? 自动实现的属性类的C#泛型 - C# Generics on Auto-Implemented Property Classes 访问自动实现属性的私有字段 - Accessing the private field of an auto-implemented property 在C#中,为什么在这种情况下使用字段与自动实现的属性会导致不同的行为? - In C#, why does using a field vs. an auto-implemented property cause different behavior in this case? 使用Mono.Cecil注入属性的自动实现的后备字段 - use Mono.Cecil inject the property's auto-implemented backing field 如何获取自动实现属性的匿名支持字段名称 - how to get the anonymous backing field name of an auto-implemented properties 拥有带有私有设置程序或私有字段且拥有属性的自动实现属性的哪个更好? - Which one is better to have auto-implemented property with private setter or private field and property just getter?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM