【发布时间】:2013-11-26 11:15:17
【问题描述】:
我的自定义属性有问题。 这是有问题的属性:
[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 中获取类属性或者它们将物理实例设置为属性时,会实例化类属性?
怎么了?
【问题讨论】:
标签: c# properties custom-properties