SORU
23 Mart 2009, PAZARTESİ


Lambda ifadesi alınıyor Özellik adı

Daha iyi bir yol lambda ifadesi ile geçirilen zaman Özellik adı için? Ben şu anda işte.

örn.

GetSortingInfo<User>(u => u.UserId);

Özelliği bir dize sadece bir memberexpression olarak onu döküm çalıştı. tüm özellikleri dizeleri, çünkü nesne kullanmak zorunda kaldım ama daha sonra olanlar için bir unaryexpression geri dönüş.

public static RouteValueDictionary GetInfo<T>(this HtmlHelper html, 
    Expression<Func<T, object>> action) where T : class
{
    var expression = GetMemberInfo(action);
    string name = expression.Member.Name;

    return GetInfo(html, name);
}

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;
}

CEVAP
23 Mart 2009, PAZARTESİ


Geçenlerde çok benzer bir şey yazın güvenli OnPropertyChanged yöntemi yapmak için yaptı.

Burada ifade döndürmek için propertyınfo nesne dönecek bir yöntem. Eğer bu ifade bir özellik değilse bir istisna atar.

public PropertyInfo GetPropertyInfo<TSource, TProperty>(
    TSource source,
    Expression<Func<TSource, TProperty>> propertyLambda)
{
    Type type = typeof(TSource);

    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()));

    if (type != propInfo.ReflectedType &&
        !type.IsSubclassOf(propInfo.ReflectedType))
        throw new ArgumentException(string.Format(
            "Expresion '{0}' refers to a property that is not from type {1}.",
            propertyLambda.ToString(),
            type));

    return propInfo;
}

source parametre derleyici yöntem çağrısı üzerine yazın çıkarım yapmak için kullanılır. Aşağıdakileri yapabilirsiniz

var propertyInfo = GetPropertyInfo(someUserObject, u => u.UserID);

Bunu Paylaş:
  • Google+
  • E-Posta
Etiketler:

YORUMLAR

SPONSOR VİDEO

Rastgele Yazarlar

  • After Effects Tutorials w/ Mikey

    After Effect

    24 HAZİRAN 2009
  • Modus Recordings

    Modus Record

    26 Kasım 2008
  • PorterRobinsonVEVO

    PorterRobins

    11 Kasım 2013