c# - 混合通用方法和扩展方法

标签 c# .net generics extension-methods

我创建了 Class1.GetChild<T>() where T : DependencyObject lib1.dll 程序集中的扩展方法。之后,所有依赖于 lib1.dll 的程序集都无法编译并出现错误:

The type 'System.Windows.DependencyObject' is defined in an assemebly that is not referenced. You must add a reference to assembly 'WindowsBase' etc...

为什么依赖程序集需要 WindowsBase,即使它们不使用 GetChild

.

重现(vs2010 .net4):

lib1.dll(引用 WindowsBase)

namespace lib1
{
    public static class Class1
    {
        public static T GetChild<T>(this DependencyObject src) where T : DependencyObject
        {
            return default(T);
        }
    }

    public static class Class2
    {
        public static int SomeExtMethod(this string src)
        {
            return 0;
        }
    }
}

lib2.dll(引用 lib1 但不是 WindowsBase)

using lib1;
class someClass
{
    void someFct()
    {
        "foo".SomeExtMethod(); // error: The type 'System.Windows.DependencyObject'
                // is defined in an assemebly that is not referenced. 
                // You must add a reference to assembly 'WindowsBase' etc..
    }
}

.

更新:

我认为混合泛型方法和扩展方法肯定有好处。我试图在以下示例中演示该问题:

// lib0.dll
namespace lib0
{
    public class Class0 { }
}

// lib1.dll
using lib0;
namespace lib1
{
    public static class Class1
    {
        public static void methodA<T>() where T : Class0 { }    // A
        public static void methodB(Class0 e) { }                // B
        public static void methodC(this int src) { }            // C
    }

    public static class Class2
    {
        public static void methodD(this String s) { }
    }
}

// lib2.dll
using lib1;
class someClass
{
    void someFct()
    {
        Class2.methodD("");  // always compile successfully
        "".methodD();        // raise the 'must add reference to lib0' error depending on config. see details below.
    }
}

A, //B, //C -> 编译成功

A, B, //C -> 编译成功

//A, B, C -> 编译成功

A, //B, C -> 引发错误

A, B, C -> 引发错误

//A表示 methodA被评论。正如 Damien 指出的那样,类型推断可能会发挥一些作用。仍然很想知道来龙去脉。

最佳答案

Microsoft 已在此处回答了您的情况: https://connect.microsoft.com/VisualStudio/feedback/details/668498/problem-with-extension-method-in-c-compiler

还有其他独立于扩展方法的用例会错误地产生此错误。

考虑一下:

  1. 在类型(例如 TP1)中定义泛型方法,在库(例如 LB1)中定义。
  2. 类型约束在某些其他库 LB2 中定义的某些类型上的泛型方法。
  3. 在 TP1 中定义另一个方法。
  4. 现在在你的库中只引用 LB1 并尝试调用 TP1 类型的第二个方法

如果您不使用 TP1,而是使用 LB1 中定义的其他类型,则不会出现错误。 此外,即使 TP1 类型的方法之一需要 LB2 中定义的类型的参数(并且您不调用此方法),它也不会产生此错误

关于c# - 混合通用方法和扩展方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/12492600/

相关文章:

c# - 从堆栈中获取所有引用和值

c# - 是否可以使用 com interop 将变体数组传递给 C#?

c# - 命名空间中不存在类型。你错过了一个大会吗?

c# - c#.net 中 throw 和 throw ex 的区别

c# - 如何将小数值显示为小数点后两位?

c - 如何在 C 编程中泛化 SSCANF 和#DEFINE

JavaFX 绑定(bind)到嵌套列

c# - 泛型与否泛型

c# - 如何强制 C# Task 对于​​给定 ID 一次仅存在一次

c# - 检查 CSV 字符串是否包含给定值 C#