Access the type of safe enumeration of class members

My class MyClass<t>has the following method

private static bool TypeHasProperty(string NameOfPropertyToMatch)
{
    var properties = typeof(t).GetProperties();
    var requiredProperty = properties.First(
            a => a.Name == NameOfPropertyToMatch);
    if (requiredProperty == null)
    {
        return false
    };

    return true;
}

This is called at the beginning of the static method:

MyClass<t>.SendToJavaScript(t InstanceOfType, string NameOfPropertyWithinType).

to make sure that it InstanceOfTypereally has a property of this name before continuing, because otherwise an exception will not be thrown until waaaaay goes along the line (this information will eventually be serialized and sent to the Javascript application, which must know which property will be available for access to this work).

I would like a good, safe type of method to call this method, which will not cause the test to fail if I decide to change the name of my properties later in the line.

For example, I do NOT want to call it like this:

MyClass<Person>.SendToJavaScript(MyPerson, "Name")

, Name LastName, Person, .

, :

MeClass<Person>.SendToJavaScript(
    MyPerson,
    TypeOf(Person).Properties.Name.ToString())

, Refactoring Name LastName, IDE .

- ? , ? ( F2)

+4
2

- :

private static bool TypeHasProperty<P>(Expression<Func<T, P>> accessor)
{
    var propertyName = ((MemberExpression)accessor.Body).Member.Name;
    var properties = typeof(T).GetProperties();
    return properties.Any(a => a.Name == propertyName);
}

:

class Foo
{
    public int Baz { get; set; }
}

MyClass<Foo>.TypeHasProperty(f => f.Baz);

: Any(), , ( ?)

, First() , .

+5

:

MeClass<Person>.SendToJavaScript(MyPerson, x => x.Name);

:

private static bool TypeHasProperty(Expression propertyExpression)
{
    var expression = GetMemberInfo(propertyExpression);
    string name = expression.Member.Name;

    return typeof(t).GetProperty(name) != null;
}

private static MemberExpression GetMemberInfo(Expression method)
{
    LambdaExpression lambda = method as LambdaExpression;
    if (lambda == null)
        throw new ArgumentNullException("method");

    MemberExpression memberExpr = null;

    if (lambda.Body.NodeType == ExpressionType.Convert)
    {
        memberExpr = 
            ((UnaryExpression)lambda.Body).Operand as MemberExpression;
    }
    else if (lambda.Body.NodeType == ExpressionType.MemberAccess)
    {
        memberExpr = lambda.Body as MemberExpression;
    }

    if (memberExpr == null)
        throw new ArgumentException("method");

    return memberExpr;
}

:

, .

, , , . ChrisWue'a .

+4

All Articles