简体   繁体   English

如何在C#中的getter和setter方法中进行验证?

[英]How can I put validation in the getter and setter methods in C#?

In C#, I can have a property without having the need to declare a private variable. 在C#中,我可以拥有一个属性而无需声明私有变量。 My VB6 code that looked like this 我的VB6代码看起来像这样

'local variable(s) to hold property value(s)
Private mvarPhoneNumber As String 'local copy
Public Property Let PhoneNumber(ByVal vData As String)
'used when assigning a value to the property, on the left side of an assignment.
'Syntax: X.PhoneNumber = 5
    mvarPhoneNumber = vData
End Property


Public Property Get PhoneNumber() As String
'used when retrieving value of a property, on the right side of an assignment.
'Syntax: Debug.Print X.PhoneNumber
    PhoneNumber = mvarPhoneNumber
End Property

can now look like this. 现在看起来像这样。

public string PhoneNumber{get;set;}

How can I put validation in the getter and setter methods in C#? 如何在C#中的getter和setter方法中进行验证? I tried adding a validation like this. 我尝试添加这样的验证。

public string PhoneNumber
        {
            get
            {
                return PhoneNumber;
            }
            set
            {
                if (value.Length <= 30)
                {
                    PhoneNumber = value;
                }
                else
                {
                    PhoneNumber = "EXCEEDS LENGTH";
                }
            }
        }

The get part of this code won't compile. 此代码的get部分将无法编译。 Do I need to revert to using a private variable? 我是否需要恢复使用私有变量?

Yes, you will have to create a backing field: 是的,您必须创建一个支持字段:

string _phoneNumber;

public string PhoneNumber
{
    get
    {
        return _phoneNumber;
    }
    set
    {
        if (value.Length <= 30)
        {
            _phoneNumber = value;
        }
        else 
        {
            _phoneNumber = "EXCEEDS LENGTH";
        }
    }
}

Keep in mind that this implementation is no different from an automatically implemented property. 请记住,此实现与自动实现的属性没有区别。 When you use an automatically implemented property you are simply allowing the compiler to create the backing field for you. 当您使用自动实现的属性时,您只需允许编译器为您创建支持字段。 If you want to add any custom logic to the get or set you have to create the field yourself as I have shown above. 如果你想在getset添加任何自定义逻辑,你必须自己创建字段,如上所示。

You do not necessarily need a local variable. 您不一定需要局部变量。 Theoretically, you could implement whatever functionality you want within a get / set property. 从理论上讲,您可以在get / set属性中实现所需的任何功能。 But, in your example, you have a recursive access of your get / set property what makes no sense in the way it is implemented. 但是,在您的示例中,您具有对get / set属性的递归访问,这对于它的实现方式没有任何意义。 So, in your concrete case, you will need a local variable, that's right. 所以,在你的具体案例中,你需要一个局部变量,这是正确的。

I would do something like this as to avoid a NullReferenceException as well as shorten the overall code. 我会做这样的事情,以避免NullReferenceException以及缩短整体代码。

public string PhoneNumber
{
    get { return _phoneNumber; }
    set 
    {
        var v = value ?? string.Empty; 
        _phoneNumber = v.Length <= 30 ? v : "EXCEEDS LENGTH"; 
    }
}
private string _phoneNumber;

Yes you do. 是的你是。 When you use the shortcut "implicit" syntax, it secretly creates a backing field called _phoneNumber for you. 当您使用快捷方式“隐式”语法时,它会秘密为您创建一个名为_phoneNumber的支持字段。 When you explicitly define your property, you need to make your own backing field. 明确定义属性时,需要创建自己的支持字段。 Right above your property definition put: 在您的属性定义正上方放置:

private string _phoneNumber;

and then in your property get use: 然后在你的财产中使用:

get
{
    return _phoneNumber;
}

Look here for several many alternatives: Acessing the backing field in an auto property 在这里查看几个替代方案: 在自动属性中访问支持字段

But the short answer is Yes, you will have to have backing field for validations. 但简短的回答是肯定的,你必须有验证的支持领域。

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

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