开发者

Extension methods in a class library project

开发者 https://www.devze.com 2022-12-27 02:16 出处:网络
I\'ve implemented some extension methods and put those in separate Class Library project. Imagine I have a simple extension method like this in class library called MD.Utility:

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

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);
        }
    } 
}

But nowhere in the web app like the App_code folder or the WebFroms code-behind page can I use this extension method. If I do something li开发者_运维知识库ke 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 
        }
    }
}

The compiler doesn't recognize IsValidEmailAddress() and there's even no IntelliSense support.

While if I put my extension method in the App_Code folder, it's usable in another .cs files in the App_code folder or the WebForms code-behind pages.


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

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


If changes are not getting recompiled when you do a solution rebuild, then it could be the type of reference you are using. If the MD.Utility project is in your web project solution, you should make the reference a "Project Reference." That will cause the build to consider that code as a dependency and therefore rebuild it when you change something. If you just include it as a DLL, then the DLL is considered external and the build will not consider it, even if it is in the same solution.


I was able to resolve it by making the extension module public. This post may be helpful: Extension methods in referenced assemblies?


In addition to adding the assembly to the references, what fixed it for me was to explicitly adding it to the file "using MD.Utility".


I've found that this can occur if the Assembly Name and Namespace of the consuming project are the same and the Common library has the same Namespace.

Seems that the compiler gets confused. Try changing them.

As noted elsewhere, you need to add the Common library to each consuming project. And the Module containing the Extension(s) in the Common library must be marked Public. Unlike Classes, Public isn't the default scope for Modules. No idea why.

0

精彩评论

暂无评论...
验证码 换一张
取 消