2010-03-18 132 views
5

我已经创建了一个属性,调用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"); 
     }; 
    } 
} 

回答

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; 
    } 
} 
+0

所以现在你可以让你的代码抛出异常。但这是否阻止你调用方法本身? – 2010-03-18 19:05:42

+0

我同意在属性中有任何行为是错误的。但问题是,为什么异常不会在上面的代码发生,答案是 - 因为当你试图访问创建它的属性类的实例。 – 2010-03-18 19:21:57

8

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

事实上,属性不应该包含在所有的行为。

+0

如果是这样的话,还有什么方法可以设置方法的安全性? – Coppermill 2010-03-18 13:57:28

+0

这是一个完全不同的话题,但你可能要看看代码访问安全性。 – 2010-03-18 14:00:48

+0

我不会推荐CAS,因为它是非常复杂的,以得到正确的和在.NET 4.0中已被弃用。 – adrianbanks 2010-03-18 14:07:52