【问题标题】:Custom attribute internal properties null c#自定义属性内部属性null c#
【发布时间】: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


    【解决方案1】:

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

    【讨论】:

      猜你喜欢
      • 2011-06-24
      • 2012-02-15
      • 2020-07-02
      • 2017-05-31
      • 1970-01-01
      • 2020-12-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多