在类库项目扩展方法 [英] Extension methods in class library project

查看:144
本文介绍了在类库项目扩展方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经实现了一些扩展方法,并把这些单独的类库项目。

I've implemented some extension methods and put those in separate Class Library project.

想象一下,我在类库这样一个简单的扩展方法调用的 MD.Utility

Imagine I have a simple extension method like this in class library called MD.Utility:

namespace MD.Utility
{
    public static class ExtenMethods
    {
        public static bool IsValidEmailAddress(this string s)
        {
            Regex regex = new Regex(@"^[\w-\.]+@([\w-]+\.)+[\w-]{2,4}$");
            return regex.IsMatch(s);
        }
    } 
}

但无处在Web应用程序一样APP_ code文件夹或WebFroms code隐藏页我不能使用这个扩展方法。如果我这样做:

But nowhere in WebApp like App_code folder or WebFroms code-behind page I can't use this Extension method. If I do like this:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using MD.Utility;

public partial class _Default : System.Web.UI.Page 
{
    protected void Page_Load(object sender, EventArgs e)
    {
        string email = "Someone@Somewhere.com";
        if (email.IsValidEmailAddress())
        {
            //To do 
        }
    }
}

编译器无法识别IsValidEmailAddress(),甚至没有IntelliSense支持。

The compiler doesn't recognize IsValidEmailAddress() and even no intellisense support.

而如果我把我的扩展方法在APP_ code文件夹,它的确定使用在APP_ code文件夹或Web窗体code隐藏页另一个CS文件。

While if I put my extension method in App_Code folder it's ok for using in another cs file in App_code Folder or Web Form code-behind pages.

推荐答案

你记得引用在Web项目添加到您的类库?

Did you remember to add a reference to your class library in the web project ?

您将需要。除此之外,您的code看起来不错,并应工作。

You will need that. Other than that, your code looks fine, and should work.

这篇关于在类库项目扩展方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆