小编Pha*_*dra的帖子

自定义 C# 属性

创建自定义属性时,会创建一个从 ValidationAttribute 类扩展而来的自定义类。

public class CustomAttribute: ValidationAttribute
    {
        
       public void Test()
        {
             Console.WriteLine("Hello World");
         }
        public override bool IsValid(object? value)
        {
            //Logic here
            if (condition)
            {
                return true;
            }
            else
                return false;

        }

      }
Run Code Online (Sandbox Code Playgroud)

假设此自定义属性放置在模型的属性之上。

[Custom]
 public string username { get; set; }
Run Code Online (Sandbox Code Playgroud)

通过将自定义放置在属性上,我实例化了自定义类。现在我的查询是

  1. 如何以及何时调用 IsValid() 方法?
  2. 为什么不调用 CustomAttribute 类中的其他方法?(在本例中为 Test() 方法)
  3. 特定方法在 CustomAttribute 类中运行的基础是什么?

c# asp.net .net-core

4
推荐指数
2
解决办法
291
查看次数

标签 统计

.net-core ×1

asp.net ×1

c# ×1