属性类不调用构造函数

时间:2010-03-18 13:38:11

标签: 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");
        };
    }
}

2 个答案:

答案 0 :(得分:8)

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

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

答案 1 :(得分:1)

实际上它失败了,但只有当你试图获取属性属性时才会失败。这是一个失败的例子:

using System;

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"));

        Func<string, string> action1 = SayHello1;
        Func<string, string> action2 = SayHello2;

        MyAttribute myAttribute1 = (MyAttribute)Attribute.GetCustomAttribute(action1.Method, typeof(MyAttribute));
        MyAttribute myAttribute2 = (MyAttribute)Attribute.GetCustomAttribute(action2.Method, typeof(MyAttribute));

        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 string MyProperty
    {
        get; set;
    }

    public string MyProperty2
    {
        get;
        set;
    }

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

        MyProperty2 = VRegKey;
    }
}