有没有办法在案例语句中避免重复?我希望我的代码尽可能动态。
public void LoadTemplate()
{
switch (this.GetTemplate)
{
case 0://Default
this.configForm.txtDSN1.Text = Configuration.Default.ServerParameters.DSN.ToString();
this.configForm.comboServer.Text = Configuration.Default.ServerParameters.Server.ToString();
this.configForm.comboDatabase.Text = Configuration.Default.ServerParameters.Database.ToString();
break;
case 1://Retail
this.configForm.txtDSN1.Text = Configuration.Retail.ServerParameters.DSN.ToString();
this.configForm.comboServer.Text = Configuration.Retail.ServerParameters.Server.ToString();
this.configForm.comboDatabase.Text = Configuration.Retail.ServerParameters.Database.ToString();
break;
default:
break;
}
}
这是我在配置类中的常数。
//Default Template
public partial class Default
{
public partial class ServerParameters
{
public const string DSN = "Default";
public const string Server = "";
public const string Database = "";
}
}
//Retail Template
public partial class Retail
{
public partial class ServerParameters
{
public const string DSN = "Retail1";
public const string Server = "";
public const string Database = "";
}
}
我是新来的C#,我可以使用一个很好的练习。谢谢
您基本上试图基于选择配置策略来定义配置行为。由于您已经有两个课程对不同的配置策略有所了解,因此您可能需要考虑重构课程以遵循策略模式。
- 创建一个具有接受您表格的方法的接口。
- 您的类默认和零售业都有该接口。该方法的每个实现都执行必要的形式配置。您甚至不再需要常数。
- 那么,这是解决策略的问题。这可以使用案例语句,数据映射甚至依赖项注入来完成。
您可以使用反射进行follwing:
string className= this.GetTemplate==0?"Default":"Retail";
Type objType = Type.GetType("Configuration."+className);
object obj = Activator.CreateInstance(objType);
objType.GetProperty(propName).GetValue(obj, null);
this.configForm.txtDSN1.Text = objType.GetProperty("ServerParameters.DSN").GetValue(obj, null).ToString();
this.configForm.comboServer.Text = objType.GetProperty("ServerParameters.Server").GetValue(obj, null).ToString();
this.configForm.comboDatabase.Text = objType.GetProperty("ServerParameters.Database").GetValue(obj, null).ToString();
这是选择需要从中获得属性的类名称,然后只需使用反射即可从中获取属性。它可能不是最好的选择,但是您可以使用它,如果它对您的应用程序产生强大的影响,则不要修改架构。
您可以通过定义ServerParameters
类型的通用提供商来使代码灵活。为此,创建这样的提供商界面:
public interface IProvider<TId, TEntity>
{
TEntity Provide(TId id);
}
然后,为此接口创建一个实现,该实现将生成一个基于模板代码或您使用的任何用于识别模板的值的ServerParameters
实例。
要做到这一点,您必须提取ServerParameters
类并仅创建一个单个定义。另外,将ServerParameters
中的属性定义更改为变量,而不是常数。
然后,您的提供商实施将是这样的:
public class ServerParametersProvider : IProvider<int, ServerParameters>
{
public ServerParameters Provide(int templateCode)
{
//For each templateCode return a ServerParameters instance with the required values.
return null;
}
}
然后,在包含LoadTemplate
方法的类中,通过接口参考注入提供商的实例。最后,您的LoadTemplate
方法看起来像这样:
public void LoadTemplate()
{
var parameters = m_Provider.Provide(GetTemplate);
configForm.txtDSN1.Text = parameters.DSN;
configForm.comboServer.Text = parameters.Server;
configForm.comboDatabase.Text = parameters.Database;
}
以这种方式,您的UI或LoadTemplate
所在的任何上下文都不会更改,而您需要提供值为值的另一个模板代码,只需更改提供商以返回具有不同值的ServerParameters
的其他实例即可。
您甚至可以通过使提供者依靠特定的模板代码来使代码更加灵活,并根据其作为参数收到的代码委派给这些提供商。