Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
143 views
in Technique[技术] by (71.8m points)

c# - What's the difference between using statement and adding a reference?

In Visual Studio, when do you have to add a reference to a dll? I always try to have a minimum of references in my projects, I try to only include the ones that are really necessary.

I would think that I only need a reference if I have a using statement in my source. But that's not always enough.

For instance, I have a very simple program that is using System and Microsoft.Practices.EnterpriseLibrary.Data:

using System;
using Microsoft.Practices.EnterpriseLibrary.Data;

public class SimpleConnection {
    private static void Main() {
        var database = DatabaseFactory.CreateDatabase();
        var command =
            database.GetSqlStringCommand(
                "select table_name from information_schema.tables");
        using (var reader = database.ExecuteReader(command)) {
            while (reader.Read()) {
                Console.WriteLine(reader.GetString(0));
            }
        }
    }
}

I would think I only have to reference System and Microsoft.Practices.EnterpriseLibrary.Data. But that's not true. If I don't reference System.Data, the code won't compile.

The type 'System.Data.Common.DbCommand' is defined in an assembly that is not referenced. You must add a reference to assembly 'System.Data, Version=2.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089'.

How can I know beforehand when I have to add a reference to something I'm not using?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

References tell the compiler where to look for types to import. Using statements tell the compiler where to look for "full names"

So you can either type

 using System.Text

 StringBuilder sb; 
 // ...

or

 System.Text.StringBuider sb;
 // ...

But either way, you must have a reference to System.dll (or is it mscorlib for StringBuilder?). Without the ref, the compiler doesn't know what types are available.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...