C# 类属性中使用属性A判断属性B是否必填逻辑操作

C# 类属性中使用属性A判断属性B是否必填逻辑操作

Posted by BY on April 27, 2023

C# 中,如何再实体类中的属性,判断其中一个属性A的值然后提示属性B为必填,类似在属性的上方加特性Required的操作? 您可以在 C# 实体类中为属性 A 添加一个自定义属性,然后在属性的 setter 方法中检查该属性的值,如果为某个特定值,就将属性 B 标记为必填。下面是一个示例代码:

csharp Copy code public class MyEntity { [MyCustomRequired] public string PropertyA { get; set; }

public string PropertyB { get; set; } }

[AttributeUsage(AttributeTargets.Property)] public class MyCustomRequiredAttribute : Attribute { public MyCustomRequiredAttribute() { }

public override bool IsValid(object value)
{
    if (value == null || value.ToString() == string.Empty)
    {
        throw new ArgumentException("PropertyB is required when PropertyA is set to a specific value.");
    }

    return true;
} }

public string PropertyA { get { return _propertyA; } set { _propertyA = value; if (value == “specific value”) { PropertyB = null; } } } 在上面的代码中,我们为 PropertyA 添加了一个自定义属性 MyCustomRequiredAttribute,它继承自 Attribute 类。该属性具有一个 IsValid 方法,在 setter 方法中可以使用该方法来检查属性 A 的值,如果为特定值,则将属性 B 标记为必填。

当您将属性 A 的值设置为特定值时,setter 方法将 PropertyB 设置为 null。这可以防止 PropertyB 的旧值在 MyCustomRequiredAttribute 中被认为是有效值。

当您在程序中使用 MyEntity 类时,如果 PropertyA 的值为特定值,则 MyCustomRequiredAttribute 将抛出一个异常,要求您将 PropertyB 的值设置为必填。