You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现propAsString函数以获取对象属性名的字符串形式?

实现方案

可以实现这类需求,核心思路是通过捕获属性访问的元信息来提取属性名称——直接传入属性值本身无法反向推导名称(因为值是独立的字符串,丢失了所属属性的关联信息),所以需要调整调用方式,传递属性访问的表达式或关联对象+属性标识。

C# 实现(表达式树方案)

利用表达式树解析属性访问逻辑,直接提取属性名称:

using System.Linq.Expressions;

public class Test
{
    public string TestProperty { get; set; }
    public string SecondTestProperty { get; set; }
}

public static class PropertyHelper
{
    public static string PropAsString<T, TProp>(Expression<Func<T, TProp>> propertyExpr)
    {
        if (propertyExpr.Body is MemberExpression memberExpr)
        {
            return memberExpr.Member.Name;
        }
        throw new ArgumentException("请传入有效的属性访问表达式");
    }
}

// 使用示例
var test = new Test();
string propName1 = PropertyHelper.PropAsString(test => test.TestProperty); // 返回 "TestProperty"
string propName2 = PropertyHelper.PropAsString(test => test.SecondTestProperty); // 返回 "SecondTestProperty"

JavaScript/TypeScript 实现

有两种常用方式,根据场景选择:

class Test {
    testProperty: string = "";
    secondTestProperty: string = "";
}

// 方式1:传入对象+属性名(最直接)
function propAsString<T, K extends keyof T>(obj: T, prop: K): string {
    return prop.toString();
}

// 方式2:传入属性访问函数(避免硬编码字符串)
function getPropName<T>(fn: (obj: T) => any): string {
    const match = fn.toString().match(/return\s+[^.]+\.([^\)]+)/);
    return match ? match[1] : "";
}

// 使用示例
const test = new Test();
const name1 = propAsString(test, "testProperty"); // 返回 "testProperty"
const name2 = getPropName<Test>(obj => obj.secondTestProperty); // 返回 "secondTestProperty"

关键说明

直接传入test.testProperty这类属性值无法实现需求,因为属性值只是一个独立字符串,没有携带任何所属属性的元数据。上述方案都是通过传递属性访问逻辑或对象+属性标识的方式,保留了足够的元信息来提取属性名称。

内容的提问来源于stack exchange,提问作者Cute pumpkin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.27 23:27:10