如何将GLAccount类字段作为参数传递给类方法TestField?
解决方案
1. 支持表达式参数调用(内外通用)
修改TestField方法,通过表达式树参数同时获取字段值与名称,完美匹配你期望的glAccount.TestField(g => g.Name)调用形式:
using System.Linq.Expressions; using System.Reflection; public class GLAccount : Table<GLAccount, Code> { [Key] public required string No { get; set; } public required string Name { get; set; } public void TestField(Expression<Func<GLAccount, string?>> fieldExpression) { // 解析表达式提取属性信息 if (fieldExpression.Body is not MemberExpression memberExpr) { throw new ArgumentException("请传入有效的属性表达式"); } var property = memberExpr.Member as PropertyInfo; if (property == null) { throw new ArgumentException("表达式必须指向类的属性"); } // 获取当前实例的属性值 string? fieldValue = property.GetValue(this) as string; string fieldName = property.Name; if (string.IsNullOrEmpty(fieldValue)) { throw new ArgumentException($"{fieldName} can not be blank in table record {this}"); } } }
调用示例:
var glAccount = new GLAccount { No = "ACC001", Name = "" }; glAccount.TestField(g => g.Name); // 抛出ArgumentException,提示Name不能为空
2. 支持类内简洁调用
如果在GLAccount类内部调用,可借助CallerArgumentExpression特性,直接传入属性值自动获取字段名称,匹配你期望的TestField(Name)形式:
using System.Runtime.CompilerServices; public class GLAccount : Table<GLAccount, Code> { [Key] public required string No { get; set; } public required string Name { get; set; } public void TestField(string? fieldValue, [CallerArgumentExpression(nameof(fieldValue))] string fieldName = "") { if (string.IsNullOrEmpty(fieldValue)) { throw new ArgumentException($"{fieldName} can not be blank in table record {this}"); } } // 类内调用示例 public void Validate() { TestField(No); TestField(Name); } }
注意:该方式仅适用于类内部,外部调用glAccount.TestField(glAccount.Name)时,fieldName会被填充为"glAccount.Name"而非"Name",不符合需求。外部调用建议优先使用第一种表达式方案。
内容的提问来源于stack exchange,提问作者Gilbert
相关产品推荐
相关产品推荐

