在 C# 中通过引用传递属性 [英] Passing properties by reference in C#
本文介绍了在 C# 中通过引用传递属性的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试执行以下操作:
I'm trying to do do the following:
GetString(
inputString,
ref Client.WorkPhone)
private void GetString(string inValue, ref string outValue)
{
if (!string.IsNullOrEmpty(inValue))
{
outValue = inValue;
}
}
这给了我一个编译错误.我认为我想要达到的目标非常清楚.基本上我希望 GetString
将输入字符串的内容复制到 Client
的 WorkPhone
属性.
This is giving me a compile error. I think its pretty clear what I'm trying to achieve. Basically I want GetString
to copy the contents of an input string to the WorkPhone
property of Client
.
是否可以通过引用传递属性?
Is it possible to pass a property by reference?
推荐答案
属性不能通过引用传递.您可以通过以下几种方法来解决此限制.
Properties cannot be passed by reference. Here are a few ways you can work around this limitation.
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");
}
2.委托
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");
}
3.LINQ 表达式
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");
}
4.反思
void GetString(string input, object target, string propertyName)
{
if (!string.IsNullOrEmpty(input))
{
var 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");
}
这篇关于在 C# 中通过引用传递属性的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文