简体   繁体   中英

Getting Property Name in C#

I have a validation class, and within this I want to verify various properties received form a web service are valid, and report a descriptive error message if not.

Currently the webservice returns all strings, and I want to convert/validate these into more useful types. The problem is I am currently passing the property name through as a string parameter in the method call. Is there a way to get the name of a property for display in the error message without passing it through as a string?

public class WebserviceAccess
{
    public MyUsefulDataObject ConvertToUsefulDataObject(WebserviceResponse webserviceResponse)
    {
        var usefulData = new MyUsefulDataObject();

        usefulData.LastUpdated = webserviceResponse.LastUpdated.IsValidDateTime("LastUpdated");
        // etc . . .
        // But I don't want to have to pass "LastUpdated" through.
        // I'd like IsValidDateTime to work out the name of the property when required (in the error message).

        return usefulData ;
    }
}

public static class WebServiceValidator
{
    public static DateTime IsValidDateTime(this string propertyValue, string propertyName)
    {
        DateTime convertedDate;

        if (!DateTime.TryParse(propertyValue, out convertedDate))
        {
            throw new InvalidDataException(string.Format("Webservice property '{0}' value of '{1}' could not be converted to a DateTime.", propertyName, propertyValue));
        }

        return convertedDate;
    }
}

Any assistance is much appreciated.

Thanks in advance.

EDIT: Using Oblivion2000's suggestion, I now have the following:

public class Nameof<T>
{
    public static string Property<TProp>(Expression<Func<T, TProp>> expression)
    {
        var body = expression.Body as MemberExpression;

        if (body == null)
        {
            throw new ArgumentException("'expression' should be a member expression");
        }

        return body.Member.Name;
    }
}

public class WebserviceAccess
{
    public MyUsefulDataObject ConvertToUsefulDataObject(WebserviceResponse webserviceResponse)
    {
        var usefulData = new MyUsefulDataObject();

        usefulData.LastUpdated = Nameof<WebserviceResponse>.Property(e => e.LastUpdated).IsValidDateTime(webserviceResponse.LastUpdated);
        // etc . . .

        return usefulData ;
    }
}

public static class WebServiceValidator
{
    public static DateTime IsValidDateTime(this string propertyName, string propertyValue)
    {
        DateTime convertedDate;

        if (!DateTime.TryParse(propertyValue, out convertedDate))
        {
            throw new InvalidDataException(string.Format("Webservice property '{0}' value of '{1}' could not be converted to a DateTime.", propertyName, propertyValue));
        }

        return convertedDate;
    }
}

Perhaps this link can give you a good way to get the parameter information.

Workaround for lack of 'nameof' operator in C# for type-safe databinding?

In Visual Studio 2011, there is a new feature to handle this: http://www.mitchelsellers.com/blogs/2012/02/29/visual-studio-11-caller-member-info-attributes.aspx

In current/older versions, you have to use tricks like Oblivion2000 posted

Here's Cℓinton Sheppard's post on this: http://handcraftsman.wordpress.com/2008/11/11/how-to-get-c-property-names-without-magic-strings/

It is so useful to me I keep it in my bookmarks. Personally, I like his static nested class way (quoted from above):

public class Sample2
{
    public static class BoundPropertyNames
    {
        public static readonly string Foo = ((MemberExpression)((Expression<Func<Sample2, int>>)(s => s.Foo)).Body).Member.Name;
    }

    public int Foo { get; set; }
}

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