csharp 用于将由非可空类型(或类似DateTime和Guid之类的结构)支持的属性标记为需要非默认值的值的属性

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了csharp 用于将由非可空类型(或类似DateTime和Guid之类的结构)支持的属性标记为需要非默认值的值的属性相关的知识,希望对你有一定的参考价值。

[AttributeUsage(AttributeTargets.Property | AttributeTargets.Field | AttributeTargets.Parameter, AllowMultiple = false)]
public class RequireNonDefaultAttribute : ValidationAttribute
{
    public RequireNonDefaultAttribute()
        : base("The {0} field requires a non-default value.")
    {
    }

    /// <summary>
    /// Override of <see cref="ValidationAttribute.IsValid(object)"/>
    /// </summary>
    /// <param name="value">The value to test</param>
    /// <returns><c>false</c> if the <paramref name="value"/> is equal the default value of an instance of its own type.</returns>
    /// <remarks>Is meant for use with primitive types or structs like DateTime, Guid, etc. Specifically ignores null values so that it can be combined with RequiredAttribute. Should not be used with Strings.</remarks>
    /// <example>
    /// //Allows you to effectively mark the field as required with out having to resort to Guid? and [Required] and then having to deal with SomeId.GetValueOrDefault() everywhere (and then test for Guid.Empty)
    /// [RequireNonDefault] 
    /// public Guid SomeId { get; set;}
    /// 
    /// //Enforces validation that requires the field beexplicitly provided, AND not be 0
    /// //Similar to [RequireNonDefault] int, except that using [Required] will add the client side validation (JS) to ensure a value is provided. I don't have client side validation for [RequireNonDefault] yet
    /// [Required][RequireNonDefault] 
    /// public int? SomeId { get; set;}
    /// 
    /// //Lets the field be optional, but if it IS provided, it can't be 0
    /// [RequireNonDefault]
    /// public decimal? Price { get; set;}
    /// 
    /// </example>
    public override bool IsValid(object value)
    {
        return value != null && !Equals(value, Activator.CreateInstance(value.GetType()));
    }
}

以上是关于csharp 用于将由非可空类型(或类似DateTime和Guid之类的结构)支持的属性标记为需要非默认值的值的属性的主要内容,如果未能解决你的问题,请参考以下文章

csharp 使用可空类型的示例。

Kotlin学习与实践 Kotlin的可控性

csharp Linq加入多个可空列

csharp Json可空字段(字符串,数组)转换器

C#可空类型(Nullable)

C#--可空类型(Nullable)