我有一个自定义属性的问题。这就是有问题的属性:
[AttributeUsage(AttributeTargets.Property, Inherited = true, AllowMultiple = false)]
public class UIProperty : Attribute
{
public UIProperty(string property, Type target) { Property = property; TargetType = target; }
private string property;
public string Property { get{return property;} set{property = value;} }
private PropertyInfo targetProperty;
public PropertyInfo TargetProperty { get { return targetProperty; } protected set { targetProperty = value; } }
private Type targetType;
public Type TargetType { get{ return targetType; } set{ targetType = value; } }
private object target; public object Target { get{return target; } set{ target = value;} }
public void SetTargetProperty(PropertyInfo targetPropertyInfo, object target)
{
targetProperty = targetPropertyInfo;
this.target = target;
}
public object TargetValue
{
get { return targetProperty.GetValue(target, null); }
set { if (!value.Equals(TargetValue)) targetProperty.SetValue(target, value, null); }
}
}
因此,如果我以这种方式取出后用SetTargetProperty设置自定义属性:
UIProperty uip = this.GetType (). GetProperty ("name"). GetCustomAttributes (typeof (UIProperty), true) [0] as UIProperty;
uip.SetTargetProperty (...);
我的属性已正确设置其目标及其属性。没有任何内容为null或未设置。但当我在代码的其他地方获取该属性时,一切都会变为null,就好像我从未设置过。。。
当我从PropertyInfo动态获取时,类Attribute会被实例化,或者它们有一个物理实例设置为该属性?
怎么了?
你说得对。正如那篇文章中所指出的,如果要构造属性对象,必须调用GetCustomAttributes或GetCustomAttribute。每次调用其中一个方法时,它都会构造指定属性类型的新实例,并根据代码中指定的值设置实例的每个字段和属性。