【发布时间】:2011-04-13 18:45:21
【问题描述】:
我试图重构这个
class AClass
{
string Property1 { get; set; }
string Property2 { get; set; }
string Property3 { get; set; }
void AMethod(AClass other)
{
if(String.IsNullOrEmpty(this.Property1))
{
this.Property1 = other.Property1;
}
if(String.IsNullOrEmpty(this.Property2))
{
this.Property2 = other.Property2;
}
if(String.IsNullOrEmpty(this.Property3))
{
this.Property3 = other.Property3;
}
}
}
我唯一能想到的是
private string GetFirstNotNullOrEmpty(string first, string second)
{
if (String.IsNullOrEmpty(first))
{
return second;
}
return first;
}
和
this.Property1 = GetFirstNotNullOrEmpty(this.Property1, other.Property1);
这并不完全等同,但可以胜任。有没有更好的重构方法?
【问题讨论】:
-
我添加了一些反射代码来处理 N 个属性。让我们知道这是怎么回事
标签: c# reflection code-snippets