【问题标题】:Custom attribute to change property value用于更改属性值的自定义属性
【发布时间】:2013-07-12 03:48:28
【问题描述】:

我有一个类叫say

Class1
  public string store { get; set; }

我想要的是用这样的东西来装饰它;

Class1
  [GetStoreNumberFromName]
  [IsNumeric]
  public string store {get; set; }

所以值可能是1234,也可能是1234 - Store name

我需要做的是检查传递的值是否只有数字。如果不是,那么在第二个示例中,我需要获取前 4 个字符并将属性值更改为该值。

因此,如果传入的值为1234 - Store Name,那么在[GetStoreNumberFromName] 的末尾,store 的值应该是1234,这样[IsNumeric] 将作为有效值传递。

【问题讨论】:

  • 在单独的类中处理这个和编写一个迭代属性的类有什么区别?属性对您的要求来说是不是有点矫枉过正?
  • @SimonWhitehead,并不过分,因为我在课堂上使用它们进行验证、错误消息以及是否需要该字段。所以我想截取该值并对其进行修改,以便正常验证可以通过该值并且不会失败

标签: c# asp.net-mvc custom-attributes


【解决方案1】:

好的.. 希望我已经理解了您的要求:

class GetStoreNumberFromNameAttribute : Attribute {
}

class Class1 {
    [GetStoreNumberFromName]
    public string store { get; set; }
}

class Validator<T>
{
    public bool IsValid(T obj)
    {
        var propertiesWithAttribute = typeof(T)
                                      .GetProperties()
                                      .Where(x => Attribute.IsDefined(x, typeof(GetStoreNumberFromNameAttribute)));

        foreach (var property in propertiesWithAttribute)
        {
            if (!Regex.Match(property.GetValue(obj).ToString(), @"^\d+$").Success)
            {
                property.SetValue(obj, Regex.Match(property.GetValue(obj).ToString(), @"\d+").Groups[0].Value);
            }
        }

        return true;
    }
}

..用法:

var obj = new Class1() { store = "1234 - Test" };
Validator<Class1> validator = new Validator<Class1>();
validator.IsValid(obj);

Console.WriteLine(obj.store); // prints "1234"

.. 显然需要对您进行一些更改.. 但它应该给您一个想法(我知道方法命名可能不是最好的.. :/)

如果我完全错过了这一点,请告诉我,我会删除。

【讨论】:

    猜你喜欢
    • 2014-06-08
    • 1970-01-01
    • 1970-01-01
    • 2018-08-19
    • 2015-03-06
    • 1970-01-01
    • 1970-01-01
    • 2021-08-02
    • 1970-01-01
    相关资源
    最近更新 更多