gpt4 book ai didi

c# - 获取属性名称

转载 作者:行者123 更新时间:2023-11-30 13:28:46 25 4
gpt4 key购买 nike

有没有办法获取传递给函数的值的属性名称?

最佳答案

你问这是否可能?

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>(this Expression<Func<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”将打印到控制台。

关于c# - 获取属性名称,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4099275/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com