English 中文(简体)
C# 允许价值观归属
原标题:C# allowed values attribute
  • 时间:2018-08-08 08:09:45
  •  标签:
  • c#

I have a Variable and I want to allow only certain values in it.

[Required(ErrorMessage = "Category must be provided")]
[Range(2, 4)]
public int Category { get; set; }

我想允许在这一变量中增加一些价值,即6和10。 我应该怎样做? 如果我能具体阐明我允许的具体价值观,是否有属性?

问题回答

Option 1

1. 提交手稿或上手递/下手递的钥匙

Option 2

Use RegularExpression data annotation like this

[RegularExpression(<>[>2>]”, ErrorMessage = “Enter 2 or 6 only” ]

<><>ption 3

Use custom validators

你们可以产生一种习俗验证归属。 例如:

using System;
using System.Collections.Generic;
using System.Web;
using System.ComponentModel.DataAnnotations;    

namespace MyProject.Models.Validation
{

    public class SpecialCategoryAttribute : ValidationAttribute
    {
        protected override ValidationResult IsValid(object value, ValidationContext validationContext)
        {

            if(value == 6 || value == 10)
            {
                return ValidationResult.Success;
            }


            return new ValidationResult("Fail");
        }
    }
}

但是,在属性之间似乎存在着冲突:Range。 允许2->4和SpecialCategory 只允许6和10。 因此,你的模式始终有效。

I think you can remove your Range and use only SpecialCategory with the values 2->4 and 6 and 10 alowed.

[RegularExpression("[2|4|6|10]")]
public int Category { get; set; }

[RegularExpression("^(2|4|6|10)$")]

公共类别{已;第3条

Starting from .NET 8.0 you can use AllowedValues and DeniedValues attributes.

例如:[AllowedValues(2,3,4)]

。 阅读更多关于<条码>的

。 阅读更多<代码>DeniedValues





相关问题
Anyone feel like passing it forward?

I m the only developer in my company, and am getting along well as an autodidact, but I know I m missing out on the education one gets from working with and having code reviewed by more senior devs. ...

NSArray s, Primitive types and Boxing Oh My!

I m pretty new to the Objective-C world and I have a long history with .net/C# so naturally I m inclined to use my C# wits. Now here s the question: I feel really inclined to create some type of ...

C# Marshal / Pinvoke CBitmap?

I cannot figure out how to marshal a C++ CBitmap to a C# Bitmap or Image class. My import looks like this: [DllImport(@"test.dll", CharSet = CharSet.Unicode)] public static extern IntPtr ...

How to Use Ghostscript DLL to convert PDF to PDF/A

How to user GhostScript DLL to convert PDF to PDF/A. I know I kind of have to call the exported function of gsdll32.dll whose name is gsapi_init_with_args, but how do i pass the right arguments? BTW, ...

Linqy no matchy

Maybe it s something I m doing wrong. I m just learning Linq because I m bored. And so far so good. I made a little program and it basically just outputs all matches (foreach) into a label control. ...

热门标签