Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
193 views
in Technique[技术] by (71.8m points)

c# - How to get and modify a property value through a custom Attribute?

I want to create a custom attribute that can be used on a property like:

[TrimInputString]
public string FirstName { get; set; }

that will be functional equivalent of

private string _firstName
public string FirstName {
  set {
    _firstName = value.Trim();
  }
  get {
    return _firstName;
  }
}

So basically every time property is set the value will be trimmed.

How do I get the value parsed, modify that value and then set the property with the new value all from within the attribute?

[AttributeUsage(AttributeTargets.Property)]
public class TrimInputAttribute : Attribute {

  public TrimInputAttribute() {
    //not sure how to get and modify the property here
  }

}
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

iam doing this , not very convincing way but its working

demo class

public class User
{

[TitleCase]
public string FirstName { get; set; }

[TitleCase]
public string LastName { get; set; }

[UpperCase]
public string Salutation { get; set; }

[LowerCase]
public string Email { get; set; }

}

Writing Attribute for LowerCase, others can be written in the similar manner

public class LowerCaseAttribute : ValidationAttribute
{
    protected override ValidationResult IsValid(object value, ValidationContext validationContext)
    {
       //try to modify text
            try
            {
                validationContext
                .ObjectType
                .GetProperty(validationContext.MemberName)
                .SetValue(validationContext.ObjectInstance, value.ToString().ToLower(), null);
            }
            catch (System.Exception)
            {                                    
            }

        //return null to make sure this attribute never say iam invalid
        return null;
    }
}

Not very elegant way as its actually implementing Validation attribute but it works


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...