问题
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