c#将新命名空间添加到项目中

时间:2011-02-15 07:43:09

标签: c#

如何在c#项目中添加命名空间?我是初学者。

if(!string.IsNullOrEmpty(result))
{
    CoderBuddy.ExtractEmails helper = new CoderBuddy.ExtractEmails(result);
    EmailsList = helper.Extract_Emails;
}

My Form1需要使用以下命名空间:

// this is the file that I need to add
using System;
using System.Collections.Generic;
using System.Text;
using System.Text.RegularExpressions;
namespace Coderbuddy
{
    public class ExtractEmails
    {
        private string s;
        public ExtractEmails(string Text2Scrape)
        {
            this.s = Text2Scrape;
        }
        public string[] Extract_Emails()
        {
            string[] Email_List = new string[0];
            Regex r = new Regex(@"[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,6}", RegexOptions.IgnoreCase);
            Match m;
            //Searching for the text that matches the above regular expression(which only matches email addresses)
            for (m = r.Match(s); m.Success; m = m.NextMatch())
            {
                //This section here demonstartes Dynamic arrays
                if (m.Value.Length > 0)
                {
                    //Resize the array Email_List by incrementing it by 1, to save the next result
                    Array.Resize(ref Email_List, Email_List.Length + 1);
                    Email_List[Email_List.Length - 1] = m.Value;
                }
            }
            return Email_List;
        }
    }
}

3 个答案:

答案 0 :(得分:5)

好吧,在你的.cs页面中添加一个using语句

using Coderbuddy;

然后您的代码可以访问此类型公开的方法。

或者,将您的winform .cs文件放在同一名称空间中(不是推荐的想法)

答案 1 :(得分:4)

将它放在代码隐藏文件的顶部: using Coderbuddy;

Read this MSDN上名称空间和程序集的介绍。

答案 2 :(得分:2)

(我假设您需要将第二个文件添加到您自己的项目中。如果它已经是您解决方案中另一个项目的一部分,那么将其添加为Darkhydro已经回答的项目参考。)

您无需向项目显式添加名称空间。您需要使用的文件的第6行中的名称空间声明确实是隐含的。

对于此示例,将一个名为ExtractEmails.cs的空白文件添加到项目中(如果文件只包含一个类定义,则在类之后命名文件),然后将该代码粘贴到其中。 Boom - 名称空间添加:)

在表单代码中,您已经在使用类的完全限定名称(也就是说,您在行中提到名称空间

CoderBuddy.ExtractEmails helper = new CoderBuddy.ExtractEmails(result);

因此您不需要“使用”声明。

如果您确实添加了“使用CoderBuddy”;在表单的.cs文件的顶部,然后该行可以更改为

ExtractEmails helper = new ExtractEmails(result);

但在这种情况下,我会保留它,因为命名空间暗示ExtractEmails代码与代码的其余部分略有分离。

相关问题