自定义属性以更改属性值 [英] Custom attribute to change property value
问题描述
我有一个叫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; }
因此,值可能是 1234
,或者可能是 1234-商店名称
So the value might be 1234
, or it might be 1234 - Store name
我需要做的是检查传递的值是否具有里面只有数字。如果不是这样,那么在第二个示例中,我需要获取前4个chrs并将属性的值更改为该值。
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.
因此,如果传入值是 1234-商店名称
,然后在 [GetStoreNumberFromName]
的末尾, store的值
应该为 1234
,以便 [IsNumeric]
将作为有效值通过。
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.
推荐答案
好吧..希望我已经理解您的要求:
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;
}
}
..用法:
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.
这篇关于自定义属性以更改属性值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!