用于更改属性值的自定义属性

时间:2013-07-12 03:48:29

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

我有一个名为say

的课程
Class1
  public string store { get; set; }

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

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

因此值可能为1234,也可能为1234 - Store name

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

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

1 个答案:

答案 0 :(得分:0)

好的..希望我理解你的要求:

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"

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

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