C# 如何为asp.net页创建扩展方法
如何在Asp.net mvc中创建像Html.DisplayTextFor这样的扩展方法?我的意思是,我需要在asp.net中为我的page类提供一个扩展,比如page.displaytext,以了解如何实现它。我创造了这个:C# 如何为asp.net页创建扩展方法,c#,asp.net,C#,Asp.net,如何在Asp.net mvc中创建像Html.DisplayTextFor这样的扩展方法?我的意思是,我需要在asp.net中为我的page类提供一个扩展,比如page.displaytext,以了解如何实现它。我创造了这个: using System; using System.Collections.Generic; using System.Linq; using System.Web; namespace System.Web.UI {
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace System.Web.UI
{
public static class PageExtension
{
public static void DisplayTextFor(this string text)
{
/*some operation*/
}
}
}
但是它不起作用。您需要在System.Web.UI.Page类中选择一个现有属性进行扩展,或者在基类和您自己的类中创建您自己的属性。您需要在System.Web.UI.Page类中选择一个现有属性进行扩展,或者在基类和您自己的类中创建您自己的属性。我猜您的意思是要扩展Page类,添加您自己的函数以在使用此时显示。Page 如果是这样,首先将PageExtension类作为您自己名称空间的一部分。那么语法是:
public static void DisplayTextFor(this Page page, string text)
{
page.Response.Write(text);
}
扩展方法第一个参数定义要扩展的类,其余参数定义调用它时发送的内容
要在页面中调用上述内容,只需:
this.Page.DisplayTextFor("hello world");
我猜您的意思是想扩展Page类,添加您自己的函数,以便在使用此页时显示。Page 如果是这样,首先将PageExtension类作为您自己名称空间的一部分。那么语法是:
public static void DisplayTextFor(this Page page, string text)
{
page.Response.Write(text);
}
扩展方法第一个参数定义要扩展的类,其余参数定义调用它时发送的内容
要在页面中调用上述内容,只需:
this.Page.DisplayTextFor("hello world");
您需要使用HtmlHelper类作为扩展参数,而不是字符串。我不会将它放在系统名称空间中。把它放在你自己的盒子里。我不明白这为什么不能在字符串上创建扩展函数。因此,您可以编写hi.displayTextFor。您已经为string而不是System.Web.UI.Page创建了一个扩展方法。您需要使用HtmlHelper类作为扩展参数,而不是string。我不会将它放在系统命名空间中。把它放在你自己的盒子里。我不明白这为什么不能在字符串上创建扩展函数。因此,您可以编写hi.displayTextFor,因为您已经为string而不是System.Web.UI.Page创建了扩展方法