加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c# – 获取属性名称

发布时间:2020-12-15 23:56:31 所属栏目:百科 来源:网络整理
导读:有没有办法获取传递给函数的值的属性名称? 解决方法 你在问这是否可行? public void PrintPropertyName(int value) { Console.WriteLine(someMagicCodeThatPrintsThePropertyName);}// x is SomeClass having a property named SomeNumberPrintInteger(x =
有没有办法获取传递给函数的值的属性名称?

解决方法

你在问这是否可行?

public void PrintPropertyName(int value) {
    Console.WriteLine(someMagicCodeThatPrintsThePropertyName);
}

// x is SomeClass having a property named SomeNumber
PrintInteger(x => x.SomeNumber);

和“SomeNumber”将打印到控制台?

如果是这样,不.这显然是不可能的(提示:PrintPropertyName(5)会发生什么?).但你可以这样做:

public static string GetPropertyName<TSource,TProperty>(this Expression<Func<TSource,TProperty>> expression) {
    Contract.Requires<ArgumentNullException>(expression != null);
    Contract.Ensures(Contract.Result<string>() != null);
    PropertyInfo propertyInfo = GetPropertyInfo(expression);
    return propertyInfo.Name;
}

public static PropertyInfo GetPropertyInfo<TSource,TProperty>> expression) {
    Contract.Requires<ArgumentNullException>(expression != null);
    Contract.Ensures(Contract.Result<PropertyInfo>() != null);
    var memberExpression = expression.Body as MemberExpression;
    Guard.Against<ArgumentException>(memberExpression == null,"Expression does not represent a member expression.");
    var propertyInfo = memberExpression.Member as PropertyInfo;
    Guard.Against<ArgumentException>(propertyInfo == null,"Expression does not represent a property expression.");
    Type type = typeof(TSource);
    Guard.Against<ArgumentException>(type != propertyInfo.ReflectedType && type.IsSubclassOf(propertyInfo.ReflectedType));
    return propertyInfo;
}

用法:

string s = GetPropertyName((SomeClass x) => x.SomeNumber);
Console.WriteLine(s);

现在“SomeNumber”将打印到控制台.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读