I understand that they are compilation time, so they cannot be universal and must be initialized with constant values. But:
Why can't they get the information you would get if you reflected what they apply to?
Why can't they accept lambda expressions, functions or delegates? Are constants a compiler?
Attributes can be a phenomenally powerful declarative tool if only one of the above was true, instead they are more like comments that can be read through reflection.
It was a kind of pomp, but I really want to know why they seem such a half-useful feature.
Here is what I wanted to do. It was assumed that this is an api for displaying values from resources through a function assigned to an attribute to the property to which the attribute is applied. Note that an abstract class should not exist if Attributes can know what they reflect. I publish this because someone wanted to know why I would like to provide functions for constructor attributes, and possibly because what I'm trying to do is already done.
public delegate void PropertyHandler(object parent, PropertyInfo property, object value); [AttributeUsage(AttributeTargets.Property, AllowMultiple = false, Inherited = true)] public class FromResourceAttribute : Attribute { private static readonly PropertyHandler m_defaultHandler = (parent, property, value) => { property.SetValue(parent, value, null); }; public PropertyHandler Handler { get; set; } public FromResourceAttribute(PropertyHandler handler) { Handler = handler; } public FromResourceAttribute() { Handler = m_defaultHandler; } } public abstract class ResourceDependent { public ResourceDependent(ResourceManager resources) { var resourceDependentProperties = from property in GetType().GetProperties() let fromResourceAttributes = property.GetCustomAttributes(typeof(FromResourceAttribute), true) where fromResourceAttributes.Count() == 1 let propertyHandler = ((FromResourceAttribute)fromResourceAttributes.Single()).Handler select new { Info = property, Handler = propertyHandler }; foreach(var property in resourceDependentProperties) { property.Handler(this, property.Info, resources.GetObject(property.Info.Name)); } } } class ResourceDependentTest : ResourceDependent { [FromResource] public string Data { get; set; } [FromResource((parent, property, value) => property.SetValue(parent, ((string)value).Split('|'), null))] public string[] Data2 { get; set; } static PropertyHandler Data3Handler = (parent, property, value) => {
c # attributes
cory
source share