[英]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 一起提供(?)
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.