c# - 属性类不调用构造函数

标签 c# attributes

我已经创建了一个名为 MyAttribute 的属性,它正在执行一些安全操作并且由于某种原因构造函数没有被触发,有什么原因吗?

public class Driver
{
    // Entry point of the program
    public static void Main(string[] Args)
    {
        Console.WriteLine(SayHello1("Hello to Me 1"));
        Console.WriteLine(SayHello2("Hello to Me 2"));

        Console.ReadLine();
    }

    [MyAttribute("hello")]
    public static string SayHello1(string str)
    {
        return str;
    }

    [MyAttribute("Wrong Key, should fail")]
    public static string SayHello2(string str)
    {
        return str;
    }


}

[AttributeUsage(AttributeTargets.Method)]
public class MyAttribute : Attribute
{

    public MyAttribute(string VRegKey)
    {
        if (VRegKey == "hello")
        {
            Console.WriteLine("Aha! You're Registered");
        }
        else
        {
            throw new Exception("Oho! You're not Registered");
        };
    }
}

最佳答案

属性在编译时应用,构造函数仅用于填充属性。属性是元数据,只能在运行时检查。

事实上,属性根本不应该包含任何行为。

关于c# - 属性类不调用构造函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2470164/

相关文章:

python - 如何从描述符将属性请求委托(delegate)给 MRO 链

javascript - javascript 中的类列表不起作用

javascript - 如何使用 jQuery 在 HTML 属性中呈现 javascript 变量

perl - "Connecting"带有哈希的 Moo 对象

C# EF 必需属性无法识别

c# - 获取 C# 字符串中字符的 ASCII 值

c# - 格式 "12345678"到 "1234-5678"

c# - 下拉列表错误

c# - 我如何使用反射找到数据注释属性及其参数

c# - 根据字符串中定义的数据类型在运行时生成结构