【发布时间】:2014-09-30 06:43:05
【问题描述】:
我有一个用 C# 编写的 WinForms 应用程序,它有很多自定义类。 其中许多类共享相似的属性和方法,并且我已经能够通过使用继承来减少编码。 但是,我的类也有很多类似的静态方法(通常,类之间的一个实现与另一个实现的唯一不同是对类本身的引用。一个非常愚蠢的例子可能是 -
public class MyClass1()
{
public string IdentifyYourself()
{
return "This is the IdentifyYourself method in " + typeof(MyClass1).Name;
}
}
public class MyClass2()
{
public string IdentifyYourself()
{
return "This is the IdentifyYourself method in " + typeof(MyClass2).Name;
}
}
有没有一种方法可以概括IdentifyYourself() 方法中的代码,这样就无需在每个实现中不断地重述Class?
如果这些不是静态方法,那么我可以做类似的事情
this.GetType().Name;
当然,“this”关键字在静态方法中是不可用的。
您可能想知道为什么这些必须是静态方法。但是,上面的示例不是我的实际代码,而是我遇到的问题的简化版本。我的代码中的一个实际示例(但仍然是较短的示例之一)如下 -
public static DataTable List(bool active = true)
{
try
{
string table = typeof(MyClass).Name;
string sqlText = "SELECT * FROM [" + table + "] WHERE Active = @Active;";
SqlCommand sqlCom = new SqlCommand(sqlText);
sqlCom.Parameters.AddWithValue("@Active", active);
DataTable results = Express.GetTable(sqlCom);
return results;
}
catch (Exception eX)
{
...
}
}
List() 实现的代码从一个类到下一个类仅在第一行有所不同
string table = typeof(MyClass).Name;
我在想,如果我能以某种方式概括这一点,我可以将代码重构如下 -
public static DataTable List(bool active = true)
{
try
{
string nameOfClass = //...some generalized way of obtained the Name of the class...//
return UtilityClass.List(nameOfClass);
}
...
}
每次我想在一个新类中实现它时,只需直接复制和粘贴几行代码,所有更详细的代码都可以放在实用程序类中。这样做的好处不仅在于避免在每个实现中键入每个类的名称,而且,如果 SQL 操作的细节需要更改,只需更改一处即可。
【问题讨论】:
标签: c# sql static-methods