使用不同但相似的对象而不分支

时间:2011-10-08 17:42:12

标签: c# linq-to-sql

多态性,代码可重用性,OOP,C#问题。我想创建一个方法,如:

private void ManyLinesOfCode(DataContext mycontext)

但是我无法将它发送给我的实际datacontexts,因为它们不是DataContext类型,而且我无法进行任何编译。

var includeCustomersFlag = Request["includeCustomersFlag"];
if (includeCustomersFlag == "1")
   {
   var context = new TypeByRepGroupDataContext();
   var lines = context.TypeByRepGroups;
   .... many lines of code
   }
else if (includeCustomersFlag == "2")
   {
   var context = new TypeByRepGroupNoChainsDataContext();
   var lines = context.TypeByRepGroupsNoChains;
   .... many lines of code
   }
else
  {
   var context = new TypeByRepGroupChainsOnlyDataContext();
   var lines = context.TypeByRepGroupsChainsOnliess;
   .... many lines of code
   }

我有一个解决方法是在我的datacontext中使用单个参数化存储过程而不是基于不同视图的多个datacontexts,但是更喜欢对上面的膨胀代码使用c#解决方案。

我正在尝试使用Albin的解决方案。我可以编译一下:

public interface IMyInterface 
{

    string arcxpostyy {get; set;}
    string arcxpostmm {get; set;}
    string CustArea {get; set;}
    string type {get; set;}
    System.Nullable<decimal> amt {get; set;}

}
partial class TypeByRepGroup : IMyInterface  { }
partial class TypeByRepGroupNoChain : IMyInterface { }
partial class TypeByRepGroupChainsOnly : IMyInterface { }

但是......它没有给我任何东西。我非常怀疑我正在使这个界面正确,但我想至少付出努力,并且不确定如何在我的代码中使用它(我的问题中的控制器片段。)互联网上没有链接到这个解决方案的实际实现我能找到的。任何人都可以完全阐明解决方案吗?

我在几周内开始担任高级软件工程师,希望能够做到这一点。

1 个答案:

答案 0 :(得分:0)

DataContexts的类型不是这里的大问题。这是你在不同的上下文中使用不同的实体。

确保TypeByRepGroupsTypeByRepGroupsNoChainsTypeByRepGroupsChainsOnliess实现通用接口。创建一个部分类,您可以在其中定义这些类实现接口。