Custom attribute to change property value

眉间皱痕 提交于 2019-12-12 01:38:31

问题


I have a class called say

Class1
  public string store { get; set; }

What I want is to decorate it with something like this;

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

So the value might be 1234, or it might be 1234 - Store name

What I need to do is check to see if the value passed has only numbers in it. If it doesn't then I need, in the second example, to grab the first 4 chrs and change the value of the property to that.

So if the passed in value was 1234 - Store Name then at the end of [GetStoreNumberFromName] the value of store should be 1234 so that [IsNumeric] will pass as valid.


回答1:


Okay.. hopefully I've understood your requirement:

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;
    }
}

..usage:

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

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

..obviously needs some changes on your end.. but it should give you an idea (I'm aware that the method naming probably isn't the best.. :/)

If I've missed the point entirely let me know and I'll delete.



来源:https://stackoverflow.com/questions/17607184/custom-attribute-to-change-property-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!