如何获得并通过自定义属性修改属性值? [英] How to get and modify a property value through a custom Attribute?

查看:102
本文介绍了如何获得并通过自定义属性修改属性值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要创建可在属性中使用如自定义属性:

  [TrimInputString]
公共字符串名字{获得;组; }

这将是功能上等同

 私人字符串_FirstName
公共字符串名字{
  集合{
    _FirstName = value.Trim();
  }
  获得{
    返回_FirstName;
  }
}

所以基本上每次属性设置值将被修剪。

我如何解析的值,修改该值,然后设置新值的属性都是从属性中?

  [AttributeUsage(AttributeTargets.Property)
公共类TrimInputAttribute:属性{  公共TrimInputAttribute(){
    //不知道如何让这里修改属性
  }}


解决方案

这不是属性如何工作。您不能访问任何属性由构造函数中附着。

如果你想使这项工作,你需要做出某种处理器类的给你传递对象,然后穿过田野去,并做一些事情取决于属性。要做的操作可以在属性中进行定义(一个抽象的基本属性是很方便的在这里),但你仍然需要手工去穿过田野应用操作。

I want to create a custom attribute that can be used on a property like:

[TrimInputString]
public string FirstName { get; set; }

that will be functional equivalent of

private string _firstName
public string FirstName {
  set {
    _firstName = value.Trim();
  }
  get {
    return _firstName;
  }
}

So basically every time property is set the value will be trimmed.

How do I get the value parsed, modify that value and then set the property with the new value all from within the attribute?

[AttributeUsage(AttributeTargets.Property)]
public class TrimInputAttribute : Attribute {

  public TrimInputAttribute() {
    //not sure how to get and modify the property here
  }

}

解决方案

That's not how attributes work. You can't access whatever the attribute is attached to from within the constructor.

If you want to make this work, you'll need to make some kind of processor class to which you pass the object, which then goes through the fields and does something depending on the attributes. The operation to do may be defined within the attribute (an abstract base attribute is handy here), but you'll still need to go through the fields by hand to apply the operation.

这篇关于如何获得并通过自定义属性修改属性值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆