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

如何在属性对应类型的方法内部获取该属性的声明名称

实现代码

你可以直接在Animal类中实现SomeCleverWayOfGettingPropertyName方法,核心逻辑通过堆栈遍历获取调用方实例,再反射遍历属性匹配当前Animal对象即可:

using System.Reflection;
using System.Diagnostics;

class Animal
{
    public void Run()
    {
        try
        {
            //try running
        }
        catch(Exception e)
        {
            MessageBox.Show(this.SomeCleverWayOfGettingPropertyName() + " failed to run");
        }
    }

    private string SomeCleverWayOfGettingPropertyName()
    {
        // 遍历调用栈,取调用Run方法的上层帧
        StackTrace stackTrace = new StackTrace();
        StackFrame? callerFrame = stackTrace.GetFrame(2);
        if (callerFrame == null) return "Unknown";
        
        // 获取持有当前Animal实例的对象实例
        object? holderInstance = callerFrame.GetThis();
        if (holderInstance == null) return "Unknown";
        
        // 遍历持有类所有Animal类型的属性,匹配当前实例
        PropertyInfo[] animalProperties = holderInstance.GetType()
            .GetProperties(BindingFlags.Public | BindingFlags.Instance)
            .Where(p => p.PropertyType == typeof(Animal))
            .ToArray();
        
        foreach (var prop in animalProperties)
        {
            var propValue = prop.GetValue(holderInstance);
            if (ReferenceEquals(propValue, this))
            {
                return prop.Name;
            }
        }
        return "Unknown";
    }
}

注意事项

  • 如果同一个Animal实例被多个属性引用,会返回第一个匹配到的属性名
  • 堆栈遍历+反射存在一定性能开销,高频调用场景可以考虑对属性查找结果做缓存
  • 代码已兼容任意持有Animal实例的类,不需要硬编码判断是否为Zoo类

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.29 16:45:00