简体   繁体   中英

Extension method to get StringLength value

I want to write an extension method to get the value of the MaximumLength property on the StringLength attribute.

For example, I have a class:

public class Person
{
    [StringLength(MaximumLength=1000)]
    public string Name { get; set; }
}

I want to be able to do this:

Person person = new Person();
int maxLength = person.Name.GetMaxLength();

Would this be possible using some sort of reflection?

If you use LINQ expressions, you can pull out the information via reflection with slightly different syntax (and you get to avoid defining an extension method on a commonly used string type):

public class StringLength : Attribute
{
    public int MaximumLength;

    public static int Get<TProperty>(Expression<Func<TProperty>> propertyLambda)
    {
        MemberExpression member = propertyLambda.Body as MemberExpression;
        if (member == null)
            throw new ArgumentException(string.Format(
                "Expression '{0}' refers to a method, not a property.",
                propertyLambda.ToString()));

        PropertyInfo propInfo = member.Member as PropertyInfo;
        if (propInfo == null)
            throw new ArgumentException(string.Format(
                "Expression '{0}' refers to a field, not a property.",
                propertyLambda.ToString()));

        var stringLengthAttributes = propInfo.GetCustomAttributes(typeof(StringLength), true);
        if (stringLengthAttributes.Length > 0)
            return ((StringLength)stringLengthAttributes[0]).MaximumLength;

        return -1;
    }
}

So your Person class might be:

public class Person
{
    [StringLength(MaximumLength=1000)]
    public string Name { get; set; }

    public string OtherName { get; set; }
}

Your usage might look like:

Person person = new Person();

int maxLength = StringLength.Get(() => person.Name);
Console.WriteLine(maxLength); //1000

maxLength = StringLength.Get(() => person.OtherName);
Console.WriteLine(maxLength); //-1

You can return something other than -1 for a property that didn't have that attribute defined. You weren't specific, but that's easy to change.

This may not be the nicest way to do this, but if you dont mind suppling the property name you need to get the Attribute value for you could use something like

public static class StringExtensions
{
    public static int GetMaxLength<T>(this T obj, string propertyName) where T : class
    {
        if (obj != null)
        {
            var attrib = (StringLengthAttribute)obj.GetType().GetProperty(propertyName, BindingFlags.Public | BindingFlags.Instance)
                    .GetCustomAttribute(typeof(StringLengthAttribute), false);
            if (attrib != null)
            {
                return attrib.MaximumLength;
            }
        }
        return -1;
    }
}

Usage:

Person person = new Person();
int maxLength = person.GetMaxLength("Name");

Otherwise using a function like Chris Sinclair mentioned in his comment would work nicely

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM