简体   繁体   English

没有私有成员的C#类成员验证

[英]C# Class member validation without having Private members

Is there a way to conduct error range checking in C# for class members, without Private members? 没有私有成员,是否可以使用C#对类成员进行错误范围检查?

1) 1)

For example here, I Need Private member for (less than/greater than checking). 例如,在这里,我需要私人会员(小于/大于检查)。

public class PageModel
{
    private int page;
    public int Page
    {
        get => page;
        set
        {
            if (value < 0) { page = 0; }
            else page = value;
        }
    }

2) 2)

If only have Public member, the get=> Page line gives SonarQube error 如果只有公共成员,则get => Page行会出现SonarQube错误

Add a way to break out of this property accessor's recursion 添加一种突破此属性访问器递归的方式

public class PageModel
{
    public int Page
    {
        get => Page;
        set
        {
            if (value < 0) { Page = 0; }
            else Page = value;
        }
    }

Just curious if there is way to conduct data validation without private member. 只是好奇是否有办法在没有私人成员的情况下进行数据验证。 Are data annotations good method also? 数据注释也是一种好方法吗? are they as safe as private members? 他们像私人会员一样安全吗?

Question answered before OP's edit OP编辑之前已回答的问题

Property is not a field, it is just shorthand for: 属性不是字段,只是以下方面的简写:

private int <>_page;
public get_Page()
{
    return <>_page;
}

public set_Page(int value)
{
     <>_page = value;
}

So setting Page like that doesn't make any sense. 因此,像这样设置Page没有任何意义。

public int Page
{
    get => Page;
}

Answering your question, no, there is no way to get rid of additional field, because there is nothing to write to if you get rid of the field. 回答您的问题,不,没有办法删除其他字段,因为如果您删除该字段,则没有任何可写的内容。

You would have to create a method such as 您将必须创建一个方法,例如

public int Page { get; set; }    
public void Validate()
{
    if(Page < 0)
       Page = 0;
}

But there are endless possibilities of doing it. 但是这样做的可能性无穷。

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

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