我将代码(c#.net 4.5)拆分为多个程序集。原因是我编写了几个重用不同代码集的应用程序。
我想将功能从程序集2扩展到程序集1 - 而不需要引用1到2。
但是我只希望在执行程序集是引用程序集1和2的另一个程序集(3)时发生扩展。
就像扩展方法一样:http://msdn.microsoft.com/en-us/library/bb383977.aspx - 但可以选择使用真实字段扩展对象。
如何?
我已经提出了一个案子。我想要的例子......
// Assembly 1
// no references to other assemblies
class ObjA
{
ObjA()
{
}
}
// Assembly 2
// reference to assembly 1
class ObjA
{
ObjA()
{
}
void SaveNow()
{
// save
}
}
// Assembly 3
// reference to assembly 1 and 2
class ObjA
{
ObjA()
{
}
}
static void SomeWhereInMyCode(ObjA x)
{
x.SaveNow(); // should be visible
}
我意识到你不能像上面那样扩展(就像部分类)对象。因此,我已经提出了这个解决方案......
// Assembly1
// no references to other assemblies
class ObjA
{
ObjBInterface objBInterface;
ObjA()
{
}
}
interface ObjBInterface
{
void Save();
}
// Assembly 2
// reference to assembly 1
class ObjBClass : ObjBInterface
{
public void SaveNow()
{
// save
}
}
// Assembly 3
// reference to assembly 1 and 2
static void SomeWhereInMyCode(ObjA a)
{
ObjBInterface b = a.objBInterface;
if(b != null)
{
ObjBClass b2 = (ObjBClass)b;
b2.SaveNow();
}
}
这可行,但不是最佳的。有更好的解决方案吗?