当项目需要引用其他dll时

时间:2013-12-18 08:55:16

标签: c# linq visual-studio generics .net-assembly

我遇到了奇怪的行为,不知道原因。我有两个项目A和B.一个引用System.Web程序集和B引用A.我将using语句添加到项目B类using A。它工作正常,直到我开始使用linq语句。 我收到编译错误

The type 'System.Web.UI.Control' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Web, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b03f5f7f11d50a3a'.

简化的示例项目。两个项目父母和孩子。父项目引用System.Web。子项目引用父项目。 父项目包含一个父级:

using System.Web.UI;

namespace Parent
{
    public static class Parent
    {
        public static T DoStuff<T>(this object obj)
            where T : Control 
        {
            return null;
        }
    }
}

子项目包含一个类Child:

using System.Collections.Generic;
using System.Linq;
using Parent;

namespace Child
{
    public class Child
    {
        void Test()
        {
            var strings = new List<string>();
            var string1 = strings.FirstOrDefault();
        }
    }
}

var string1 = strings.First();引发了异常。我只想在Child项目中添加对System.Web的引用,一切正常。但我想理解为什么它会像这样工作。 如果我将父类更改为:

public static class Parent
{
    public static Control DoStuff(this object obj)
    {
        return null;
    }
}

我没有使用泛型,而是直接使用Control类。它工作正常。 有什么想法吗?

已编辑:var string1 = strings.FirstOrDefault();

1 个答案:

答案 0 :(得分:3)

如果您引用一个项目,它会添加对其编译的dll的引用。 但是,仅仅因为您引用了一个dll并不会使您的项目以递归方式引用引用的dll引用的所有dll。

假设您将项目B的引用添加到项目A.虽然项目B引用了System.Web,但它不会在项目A中自动引用它。 如果系统递归地添加对dll的引用,你最终会得到大量不需要的引用。

这就是为什么你仍然需要在项目A中引用所有必要的程序集手动,以便能够使用项目B中的所有内容。

相关问题