简体   繁体   English

C#属性设置如果

[英]C# property set if

Can I make a property in c# class that has no field, but I still can check the value and set it only if match? 我可以在c#类中创建一个没有字段的属性,但我仍然可以检查该值并仅在匹配时设置它?

I mean something like this: 我的意思是这样的:

public int Num
{
    get;
    set if value > 0 && value < 100;
}

I know that I can do this: 我知道我可以这样做:

private int num;
public int Num
{
    get
    {
        return num;
    }
    set
    {
        if (value > 0 && value < 100)
            num = value;
    }
}

But I want to do it without using a field, and just using property. 但我想在不使用字段的情况下进行,只使用属性。 Is it possible? 可能吗?

To be clear: btw; 要明确: 顺便说一下; it's not that the property won't be set to that value, it's just a different way to look at your question. 并不是该属性不会被设置为该值, 它只是一种不同的方式来查看您的问题。

You can use attributes, but you'll need a way to validate them. 您可以使用属性,但您需要一种方法来验证它们。 For instance; 例如; the Range attribute: Range属性:

[Range(0,100, ErrorMessage = "Value for {0} must be between {1} and {2}.")]
public int Num {get; set;}

So, this is typically used in MVC or EF like applications where the attributes are being checked by that particular framework. 因此,这通常用于MVC或EF类应用程序,其中属性由特定框架检查。

There is some more info about that subject here: https://msdn.microsoft.com/en-us/library/cc668215(v=vs.110).aspx 这里有关于该主题的更多信息: https//msdn.microsoft.com/en-us/library/cc668215(v = vs.110).aspx

It can also work in MVVM WPF applications, but again, you'll need a framework for that. 它也可以在MVVM WPF应用程序中工作,但同样,你需要一个框架。

btw; 顺便说一句, it's not that the property won't be set to that value, it's just a different way to look at your question. 并不是该属性不会被设置为该值,它只是一种不同的方式来查看您的问题。

So if your use case is actually how to restrict and easily apply some business rules on a view or data-model, this is an accepted method. 因此,如果您的用例实际上是如何限制并轻松地在视图或数据模型上应用某些业务规则,则这是一种可接受的方法。 If you keep it to your original question can I do a conditional set without an if and a field? 如果你保留原来的问题can I do a conditional set without an if and a field? , the answer is no. , 答案是不。

Some more attributes can be found here . 这里可以找到更多属性。

I think the answer is no. 我认为答案是肯定的。 You may want to see this one and this one to know why. 您可能希望看到这一个 ,这一个知道为什么。

Fields are ordinary member variables or member instances of a class. 字段是普通成员变量或类的成员实例。 Properties are an abstraction to get and set their values. 属性是获取和设置其值的抽象。

by doing the first block, you just break shorthand that already defined in C# and if you want to implement that idea, I think @Stefan proposed a good one. 通过执行第一个块,您只需打破已在C#中定义的速记,如果您想实现该想法,我认为@Stefan提出了一个好的。

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

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