本文介绍了如何获得财产get或set体财产属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

是否有可能获得财产的财产属性获取或设置身体的没有的StackFrame

例如:

  [SomeAttribute]
公众诠释SomeProp
{
    得到
    {
        // SomeAttribute获取上设置该属性
    }
    组
    {
        // SomeAttribute获取上设置该属性
    }
}


解决方案

您可以写这样的功能,而不是由字符串lliterals由前pression获得属性名称

 公共字符串项目(这件T OBJ,防爆pression<&Func键LT; T,对象>>前pression)
{
    如果(如pression.Body是MemberEx pression)
    {
        返回((MemberEx pression)前pression.Body).Member.Name;
    }
    如果(如pression.Body是UnaryEx pression)
    {
        返回((MemberEx pression)((UnaryEx pression)前pression.Body).Operand).Member.Name;
    }
    抛出新的InvalidOperationException异常();
}

用法:

 公众诠释SomeProp
{
  得到
  {
     VAR attribs =
           。this.GetType()的getProperty(this.Item(O => o.SomeProp))。属性;
  }
}

Is it possible to get attribute on property in property get or set body without StackFrame?

for example

[SomeAttribute]
public int SomeProp
{
    get
    {
        //Get of SomeAttribute is set on this property
    }
    set
    {
        //Get of SomeAttribute is set on this property
    }
}
解决方案

You can write a function like this and get the property name by an expression not by string lliterals

public string Item(this T obj, Expression<Func<T, object>> expression) 
{
    if (expression.Body is MemberExpression)
    {
        return ((MemberExpression)expression.Body).Member.Name;
    }
    if (expression.Body is UnaryExpression)
    {
        return ((MemberExpression)((UnaryExpression)expression.Body).Operand).Member.Name;
    }
    throw new InvalidOperationException();
}

Usage:

public int SomeProp
{
  get 
  { 
     var attribs = 
           this.GetType().GetProperty(this.Item(o => o.SomeProp)).Attributes;
  }
}

这篇关于如何获得财产get或set体财产属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

10-13 12:53