0

我对自定义属性有疑问。这是有问题的财产:

[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 吗?

怎么了?

4

1 回答 1

1

你说的对。正如那篇文章中所指出的,如果要构造属性对象,则必须调用 GetCustomAttributes 或 GetCustomAttribute。每次调用其中一个方法时,它都会构造指定属性类型的新实例,并根据代码中指定的值设置每个实例的字段和属性。

于 2013-11-26T11:42:39.290 回答