您的位置:首页 > 其它

扩展方法必须在非泛型静态类中定义

2016-07-27 10:25 316 查看
扩展方法必须在非泛型静态类中定义:
public  class CustomerHelperClass
{
public static MvcHtmlString CreateImage(string imageSource, string altText, string width, string height)
{
//通过TagBulider创建标签
TagBuilder imageTag = new TagBuilder("img");
//MergeAttribute添加新特性
imageTag.MergeAttribute("src", imageSource);
imageTag.MergeAttribute("alt", altText);
imageTag.MergeAttribute("width", width);
imageTag.MergeAttribute("height", height);
//MvcHtmlString.Create使用指定的文本值,创建HTML编码的字符串
return MvcHtmlString.Create(imageTag.ToString(TagRenderMode.SelfClosing));
}
public static MvcHtmlString CreateImage(this HtmlHelper htmlHelper, string imageSource, string altText, string height, string width)
{
//通过TagBuilder创建标签
TagBuilder imageTag = new TagBuilder("img");
imageTag.MergeAttribute("src",imageSource);
imageTag.MergeAttribute("alt", altText);
imageTag.MergeAttribute("height", height);
imageTag.MergeAttribute("width", width);
//MvcHtmlString.Create使用指定的文本值,创建HTML编码的字符串
return MvcHtmlString.Create(imageTag.ToString(TagRenderMode.SelfClosing));
}
}
在上面的这段代码中在编译时会出现“扩展方法必须在非泛型静态类中定义”,出现错误的原因就在于
public  class CustomerHelperClass
扩展方法所在的这个类为非静态的,只需将扩展方法所在的类定义成静态类即可,修改如下:
public static class CustomerHelperClass
因此在使用静态方法时需要注意:

1、扩展方法即静态方法。
2、扩展方法必须在静态类里面。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  标签 public