我开始学习C#而且我遇到了一个小问题。我不知道是否有我想要做的解决方案,或者我必须以不同的方式做到这一点。 无论如何,我正在尝试修改方法返回的类变量的值。 下面的代码或多或少地显示了我想要做的事情。
public Class AClass
{
private SomeClass A;
private SomeClass B;
private SomeClass C;
private SomeClass D;
private enum SomeEnum {A, B, C, D};
private void SomeMethod(SomeEnum theEnum, SomeClass theNewValue){
SomeClass oldValue = GetSomeClass(theEnum);
oldValue = theNewValue;
}
private SomeClass GetSomeClass (SomeEnum theEnum){
switch(theEnum){
case A:
return A;
case B:
return B;
case C:
return C;
case D:
return D;
}
return null;
}
}
你们有任何解决方案或替代方案吗?
答案 0 :(得分:2)
你快到了。你只需要直接覆盖A,B,C或D:
public Class AClass
{
private SomeClass A;
private SomeClass B;
private SomeClass C;
private SomeClass D;
private enum SomeEnum {A, B, C, D};
public void UpdateInstance (SomeEnum theEnum, SomeClass newClass)
{
switch(theEnum)
{
case SomeEnum.A:
A = newClass;
break;
case SomeEnum.B:
B = newClass;
break;
case SomeEnum.C:
C = newClass;
break;
case SomeEnum.D:
D = newClass;
break;
}
}
}
但是switch语句很难看,并且只能随着代码的复杂性而增长。最好用功能字典替换它:
private readonly Dictionary<SomeEnum, Action<SomeClass>> instanceUpdaters =
new Dictionary<SomeEnum, Action<SomeClass>>
{
{ SomeEnum.A, x => A = x },
{ SomeEnum.B, x => B = x },
{ SomeEnum.C, x => C = x },
{ SomeEnum.D, x => D = x }
};
public void UpdateInstance (SomeEnum theEnum, SomeClass newClass)
{
instanceUpdaters[theEnum](newClass);
}
答案 1 :(得分:0)
public interface ISomeClass
{
/// <summary>
/// eample class method
/// </summary>
/// <returns></returns>
string doSomething();
}
public class SomeClassA : ISomeClass
{
public string doSomething()
{
return "A";
}
}
public class SomeClassB : ISomeClass
{
public string doSomething()
{
return "B";
}
}
public class SomeClassC : ISomeClass
{
public string doSomething()
{
return "C";
}
}
public class SomeClassD : ISomeClass
{
public string doSomething()
{
return "D";
}
}
public class Class1
{
private SomeClassA A;
private SomeClassB B;
private SomeClassC C;
private SomeClassD D;
private enum SomeEnum { A, B, C, D };
private void SomeMethod(SomeEnum theEnum, ISomeClass theNewValue)
{
ISomeClass oldValue = GetSomeClass(theEnum);
oldValue = theNewValue;
}
private ISomeClass GetSomeClass(SomeEnum theEnum)
{
switch (theEnum)
{
case SomeEnum.A:
return A;
case SomeEnum.B:
return B;
case SomeEnum.C:
return C;
case SomeEnum.D:
return D;
}
return null;
}
}
此外,您可以使用动态类创建来不使用开关。
答案 2 :(得分:-1)
一种可能的方法是反思:
private SomeClass GetSomeClass(SomeEnum theEnum)
{
return (SomeClass)GetType().GetField(theEnum.ToString(), BindingFlags.NonPublic | BindingFlags.Instance).GetValue(this);
}