Jro*_*nny 0 c# properties pass-by-reference
我不确定我是否正确地提出了这个问题.如果我错了,请纠正我.
无论如何,我们想在页面生命周期的不同阶段使用变量的值.
所以,例如,
public partial class TestUserControl: UserControl{
public TestUserControl(){
Objects = new List<object>(){
Property1,
Property2,
Property3
};
}
public int Property1 { get; set; }
public bool Property2 { get; set; }
public string Property3 { get; set; }
public List<object> Objects { get; set; }
protected override OnLoad(EventArgs e){
foreach(var item in Objects){
Page.Controls.Add(new LiteralControl(item.ToString() + "<br/>"));
}
}
}
Run Code Online (Sandbox Code Playgroud)
因此,如果我们说Property1,Property2,Property3的值是在标记上写的那样设置的,那么我们如何才能在需要时使用属性的值?
在构造函数上,而不是属性的值将在列表中列出,只有属性的名称将被列出,因此它们的当前值将用于OnLoad.
非常感谢.
public partial class TestUserControl: UserControl{
public TestUserControl(){
Objects = List<Func<object>>{
() => Property1,
() => Property2,
() => Property3
};
}
public int Property1 { get; set; }
public bool Property2 { get; set; }
public string Property3 { get; set; }
public List<Func<object>> Objects { get; set; }
protected override OnLoad(EventArgs e){
foreach (var item in Objects) {
//Here is the problem... can we get the variable name using this approach?
//We have tried some other ways like reflection and expressions but to no avail. Help please =)
string key = GetVariableName(item());
string value = item() == null ? string.Empty : item().ToString();
Page.Controls.Add(new LiteralControl(key + " : " + value + "<br/>"));
}
}
}
Run Code Online (Sandbox Code Playgroud)
您可以通过引用(使用)而不是属性来传递变量.此外,"ref-ness"仅适用于方法的持续时间:它将参数和参数别名,但如果将参数值复制到另一个变量,则该另一个变量不是别名.ref
目前还不清楚你想要做什么,但你可以使用代表:
Objects = new List<Func<object>>(){
() => Property1,
() => Property2,
() => Property3
};
Run Code Online (Sandbox Code Playgroud)
然后:
protected override OnLoad(EventArgs e){
foreach(var itemRetriever in Objects){
Page.Controls.Add(new Literal(itemRetriever().ToString() + "<br/>"));
}
}
Run Code Online (Sandbox Code Playgroud)
虽然这很糟糕 - 如果可以,我会尝试寻找替代设计.