在下面的代码中,我想知道如何识别正在执行的类,以便通过应用switch case来个性化它。我试过检查Param T,但它对我没用。
提前致谢!
ExecuteCalculationsWith<RoofMaterialQuantityCalculator>();
ExecuteCalculationsWith<WallMaterialQuantityCalculator>();
ExecuteCalculationsWith<CurtainWallPanelsMaterialQuantityCalculator>();
ExecuteCalculationsWith<FloorMaterialQuantityCalculator>();
private void ExecuteCalculationsWith<T>() where T : MaterialQuantityCalculator, new()
{
T calculator = new T();
calculator.SetDocument(m_doc);
calculator.CalculateMaterialQuantities();
switch (typeof(T))
{
case RoofMaterialQuantityCalculator:
calculator.InsertDataTableintoSQLTableusingSQLBulkCopy();
break;
case WallMaterialQuantityCalculator:
calculator.InsertDataTableintoSQLTable_walls();
break;
default:
break;
}
}
答案 0 :(得分:2)
如果MaterialQuantityCalculator
类有一个abstract
方法,例如InsertDataTableIntoSqlTable()
,然后每个派生计算器实现它,那么你的泛型方法将如下所示,这将是一个更好的解决方案:
private void ExecuteCalculationsWith<T>()
where T : MaterialQuantityCalculator, new()
{
T calculator = new T();
calculator.SetDocument(m_doc);
calculator.CalculateMaterialQuantities();
calculator.InsertDataTableIntoSqlTable();
}
public abstract class MaterialQuantityCalculator
{
public abstract void InsertDataTableIntoSqlTable();
// rest is omitted for clarity
}
public class RoofMaterialQuantityCalculator : MaterialQuantityCalculator
{
public override void InsertDataTableIntoSqlTable()
{
// Content of InsertDataTableintoSQLTableusingSQLBulkCopy() method comes here
}
// rest is omitted for clarity
}
public class WallMaterialQuantityCalculator : MaterialQuantityCalculator
{
public override void InsertDataTableIntoSqlTable()
{
// Content of InsertDataTableintoSQLTable_walls() method comes here
}
// rest is omitted for clarity
}
答案 1 :(得分:0)
您可以使用typeof
运算符。但你不能在switch
个实例上Type
(您可能 switch
在Name
个实例的Type
属性上,但我不建议这样做,因为它&#39;不可靠/可维护/可重构)
尝试这样:
private void ExecuteCalculationsWith<T>() where T : MaterialQuantityCalculator, new()
{
T calculator = new T();
calculator.SetDocument(m_doc);
calculator.CalculateMaterialQuantities();
Type t = typeof(T);
if (t == typeof(RoofMaterialQuantityCalculator))
calculator.InsertDataTableintoSQLTableusingSQLBulkCopy();
else if (t == typeof(WallMaterialQuantityCalculator))
calculator.InsertDataTableintoSQLTable_walls();
}