我对自定义属性有疑问。这是有问题的财产:
[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,就好像我从未设置过一样......
当我从 PropertyInfo 动态获取类属性时,或者它们将物理实例设置为属性时,会实例化类 Attribute 吗?
怎么了?