如何使用C#反射获取类方法内部操作的目标成员对应属性名称
问题结论
你的需求完全可以实现,针对你提供的两种类结构分别有对应的实现方案:
1. 原始类结构(无封装私有属性)
常规反射API无法读取方法内部执行逻辑,要实现只能通过解析ApplyValue方法的IL字节码获取赋值的目标属性,开发成本较高,且如果后续方法逻辑修改,解析逻辑很容易失效,不推荐使用。
2. 调整后类结构(封装为私有属性)
这个结构优化后有多种低成本的实现方案,以下是优先级从高到低的可选方案:
方案1:自定义Attribute标记(最推荐)
首先定义一个标记用的特性类:
[AttributeUsage(AttributeTargets.Property)] public class TargetPropertyAttribute : Attribute { public string PropertyName { get; } public TargetPropertyAttribute(string propertyName) { PropertyName = propertyName; } }
给你的封装属性加上标记:
[TargetProperty(nameof(MeshRenderer.material))] private Material m_valueProperty { get => m_Target.material; set => m_Target.material = value; }
然后通过反射读取特性即可拿到结果:
using System.Reflection; private string GetTargetFullName(Type targetNodeType) { // 拿到m_Target的类型(你已有实现) Type targetComponentType = GetTargetComponentType(targetNodeType); if (targetComponentType == null) return null; // 读取私有属性的标记 PropertyInfo valueProp = targetNodeType.GetProperty("m_valueProperty", BindingFlags.NonPublic | BindingFlags.Instance); if (valueProp == null) return null; TargetPropertyAttribute attr = valueProp.GetCustomAttribute<TargetPropertyAttribute>(); return attr == null ? null : $"{targetComponentType.Name}.{attr.PropertyName}"; }
这个方案性能最高、稳定性最好,后续属性逻辑修改只要同步更新Attribute标记即可,不会出现解析异常。
方案2:接口约定暴露
给你的公共接口IMaterialTarget新增一个属性定义:
public interface IMaterialTarget { string TargetValueFullName { get; } // 其他原有接口定义... }
在实现类中直接返回对应值:
public string TargetValueFullName => $"{nameof(MeshRenderer)}.{nameof(MeshRenderer.material)}";
不需要反射,直接读取接口属性即可拿到结果,性能最优,适合节点数量较少、修改成本低的场景。
方案3:解析属性IL(无需修改业务代码)
如果不想修改现有业务代码,也可以通过解析私有属性getter的IL字节码,自动获取调用的目标属性名,实现代码如下:
using System.Reflection; using System.Linq; private string GetTargetFullName(Type targetNodeType) { Type targetComponentType = GetTargetComponentType(targetNodeType); if (targetComponentType == null) return null; PropertyInfo valueProp = targetNodeType.GetProperty("m_valueProperty", BindingFlags.NonPublic | BindingFlags.Instance); if (valueProp == null) return null; MethodInfo getMethod = valueProp.GetGetMethod(true); byte[] ilBytes = getMethod.GetMethodBody().GetILAsByteArray(); // 遍历IL找到getter方法调用的目标属性getter for (int i = 0; i < ilBytes.Length; i++) { // 0x28为call指令的操作码 if (ilBytes[i] == 0x28) { int methodToken = BitConverter.ToInt32(ilBytes, i + 1); MethodInfo calledMethod = (MethodInfo)targetNodeType.Module.ResolveMethod(methodToken); // 判断是否为属性的getter方法 if (calledMethod.IsSpecialName && calledMethod.Name.StartsWith("get_")) { string propertyName = calledMethod.Name.Substring(4); return $"{targetComponentType.Name}.{propertyName}"; } } } return null; }
该方案无需修改业务代码,但仅适合属性逻辑固定为直接返回m_Target对应属性的场景,如果后续属性逻辑中新增了分支判断、缓存等逻辑,IL解析会失效。
内容的提问来源于stack exchange,提问作者Robert J Homewood
相关产品推荐
相关产品推荐

