重写的扩展方法需要程序集引用

时间:2015-02-10 21:12:21

标签: c# .net generics .net-4.5 extension-methods

这似乎很奇怪,除非我遗漏了什么......

public static string ToDomainSolarSystemCelestial(this TypeMapper<string> m)
{
    // Does not reference any other assemblies - straight string to string mapping.
    return m.Source
}

public static Universe.SolarSystemCelestial ToDomainSolarSystemCelestial(this TypeMapper<Db.SolarSystemCelestial> m)
{
     // Maps between a database and business object. 
     // Requires a reference to the Db assembly.
     return new Universe.SolarSystemCelestial()
     {
         Id = m.Source.Id,
         // etc
     }
}

这两种扩展方法都在同一个类中定义。第二个覆盖需要知道什么是Db.SolarSystemCelestial,因此它需要对包含程序集的引用。然而,第一个是直接字符串到字符串映射。

但如果我这样做......

var x = Mapper.Map("x").ToDomainSolarSystemCelestial();

..使用没有依赖关系的重载,Visual Studio会抱怨以下消息:

The type Db.SolarSystemCelestial is not defined in an assembly that is referenced. You must add a reference to assembly Db, Version 1.0.0.0...

如果我更改其中一种方法的名称问题就会消失。除了更改名称之外,还有其他方法吗?理想情况下,我希望覆盖具有相同的名称,但处理不同的类型。

感谢。

注意:有关于查找未引用的程序集的问题,但在这种情况下,我询问扩展方法的编译,而不仅仅是缺少程序集引用。

1 个答案:

答案 0 :(得分:1)

Universe.SolarSystemCelestial的基类是什么?

它与返回类型有关,或者在不同的程序集中,或者它的一个基本类型,或者它公开公开的类型在另一个程序集中。

编辑:

在用额外的评论再次阅读问题后,问题如@dbugger所述

一种解决方法是将扩展方法放在不同的命名空间中,并且在调用代码时只添加所需的命名空间。所以编译器只看到一个。