2015-04-06 43 views
1

我有这样的习俗在这里属性在那里做一些逻辑创建自定义的逻辑属性里面

[AttributeUsage(AttributeTargets.All)] 
public class CustomAttribute : Attribute 
{ 
    public CustomAttribute() 
    { 
     bool foo = false; 
     if (foo) 
      Console.WriteLine ("TRUE"); 
    } 
} 

的话,我想用它在我的组件类这样

[Custom] 
public class Component 
{ 
    public void Test() 
    { 
     console.log("test"); 
    } 
} 

,所以我想要什么每次我创建该组件类的实例时,它都会基本上调用或执行属性中的代码以执行某些逻辑,但问题是,它不会执行我的自定义属性类中的代码。我知道我做错了,任何人都知道如何做到这一点?

+0

下面是一个很好的示例,显示何时运行属性构造函数:http://stackoverflow.com/a/1168590/390819。如果你想在每次创建一个'Component'的新实例时执行代码,那么为什么不在'Component'构造函数中使用这些代码呢? – GolfWolf

回答

1

当类被实例化时,它不会固有地调用与你的属性绑定的任何代码,甚至实例化它。只有在您使用反射调用属性时才会实例化属性。如果您希望在构建类时处理属性,则必须在Component类的构造函数中调用一个方法,该方法使用反射来分析类中的属性。

理想的方法是改为从具有构造逻辑基类继承:

public class Component : CustomBase 
{ 
    public void Test() 
    { 
     console.log("test"); 
    } 
} 

public abstract class CustomBase 
{ 
    public CustomBase() 
    { 
     bool foo = false; 
     if (foo) 
      Console.WriteLine ("TRUE"); 
    } 
} 
1

你需要调用:

object[] attributes = typeof(MyClass).GetCustomAttributes(true); 

的地方,因为这是触发代码属性构造函数来运行。 您可以在属性类中创建一个方法,该方法调用此行,并在您的Component中调用属性方法。

1

正如Jason和Cristina所说的,你需要考虑到自定义属性的代码反射。如果您阅读下面的代码(从第18行到第24行),您可以看到一些注释掉的代码,其中列出了与某个类型关联的所有CustomAttribute。

using System; 
using System.Collections.Generic; 
using System.ComponentModel.Design; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 


namespace CustomAttributeTest 
{ 
    class Program 
    { 
     static void Main(string[] args) 
     { 
      var customCompo = new Component(); 
      customCompo.Test(); 

      //System.Reflection.MemberInfo info = typeof(Component); 
      //object[] attributes = info.GetCustomAttributes(true); 
      //for (int i = 0; i < attributes.Length; i++) 
      //{ 
      // System.Console.WriteLine(attributes[i]); 

      //} 
      Console.ReadLine(); 

     } 
    } 

    [CustomAttribute(true)] 
    public class Component 
    { 
     public void Test() 
     { 

      System.Console.WriteLine("Component contructed"); 

      var member = typeof(Component); 
      foreach (object attribute in member.GetCustomAttributes(true)) 
      { 
       if (attribute is CustomAttribute) 
       { 
        //noop 
       } 
      } 


     } 
    } 


    [AttributeUsage(AttributeTargets.All)] 
    public class CustomAttribute : Attribute 
    { 

     private bool _value; 

     //this constructor specifes one unnamed argument to the attribute class 
     public CustomAttribute(bool value) 
     { 
      _value = value; 
      Console.WriteLine(this.ToString()); 

     } 


     public override string ToString() 
     { 
      string value = "The boolean value stored is : " + _value; 
      return value; 
     } 




    } 



}