属性不能通过引用传递。您可以通过以下几种方法来解决此限制。
1.返回值2.委托string GetString(string input, string output){ if (!string.IsNullOrEmpty(input)) { return input; } return output;}void Main(){ var person = new Person(); person.Name = GetString("test", person.Name); Debug.Assert(person.Name == "test");}
3. LINQ表达式void GetString(string input, Action<string> setOutput){ if (!string.IsNullOrEmpty(input)) { setOutput(input); }}void Main(){ var person = new Person(); GetString("test", value => person.Name = value); Debug.Assert(person.Name == "test");}
4.反思void GetString<T>(string input, T target, expression<Func<T, string>> outExpr){ if (!string.IsNullOrEmpty(input)) { var expr = (Memberexpression) outExpr.Body; var prop = (PropertyInfo) expr.Member; prop.SetValue(target, input, null); }}void Main(){ var person = new Person(); GetString("test", person, x => x.Name); Debug.Assert(person.Name == "test");}
void GetString(string input, object target, string propertyName){ if (!string.IsNullOrEmpty(input)) { prop = target.GetType().GetProperty(propertyName); prop.SetValue(target, input); }}void Main(){ var person = new Person(); GetString("test", person, nameof(Person.Name)); Debug.Assert(person.Name == "test");}
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)