我有一些像这样的代码,
using (SPLimitedWebPartManager wpMngr = newWeb.GetLimitedWebPartManager(newWeb.Url + "/default.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
{
var wp = new WebPart1();
wp.ChromeType = PartChromeType.None;
wpMngr.AddWebPart(wp, "left", 0);
}
和
using (SPLimitedWebPartManager wpMngr = newWeb.GetLimitedWebPartManager(newWeb.Url + "/default.aspx", System.Web.UI.WebControls.WebParts.PersonalizationScope.Shared))
{
var wp = new WebPart2();
wp.ChromeType = PartChromeType.None;
wpMngr.AddWebPart(wp, "left", 0);
}
依此类推......我有10个像这样的代码行,如何从中提取出一个方法呢?
AddWebPart(SPWeb newWeb, string zone, Type what ?)
{
not sure how to handle passing object WebPart1() and WebPart2 and so on...
}
AddWebPart(web, "left", WebPart1);
AddWebPart(web, "left", WebPart2);
修改
所有对象WebPartn的类型为System.Web.UI.WebControls.WebParts.WebPart
答案 0 :(得分:3)
如果所有WebPart共享WebPart作为公共基类,那么您可以这样做;
AddWebPart(SPWeb newWeb, string zone, WebPart webPart)
{
webPart.ChromeType = PartChromeType.None;
wpMngr.AddWebPart(webPart, "left", 0);
}
AddWebPart(web, "left", new WebPart1());
AddWebPart(web, "left", new WebPart2());
注意:这仅适用于您只是再次调用基类WebPart的一部分的方法...假设您正在使用它。
答案 1 :(得分:2)
您可以为此创建通用方法并处理多种数据类型如果我在这里正确地使用了
解决方案是创建通用方法,如下所示
AddWebPart<T>(SPWeb newWeb, string zone, T webPart)
{
not sure how to handle passing object WebPart1() and WebPart2 and so on...
}
注意:可能是语法错误,您可以在msdn上查看有关创建genric方法的信息。
如果两个人都离开同一个基类,你也可以这样做:
AddWebPart(SPWeb newWeb, string zone, BaseWebPart webPart)
{
not sure how to handle passing object WebPart1() and WebPart2 and so on...
}
BaseWebPart:这是webpart的基础知识
答案 2 :(得分:0)
using System;
using System.Collections.Generic;
using System.IO;
using System.Xml.Serialization;
namespace Test
{
public class SPLimitedWebPartManager : IDisposable
{
public void Dispose() { }
internal void AddWebPart(WebPart wp,string p1,int p2) { }
}
public class WebPart
{
public object ChromeType { get; set; }
}
public class WebPart1 : WebPart {}
public class WebPart2 : WebPart {}
internal class Program
{
public void AddWebPart( WebPart w)
{
using (SPLimitedWebPartManager wpMngr = new SPLimitedWebPartManager() )
{
var wp = w;
wp.ChromeType = "stuff";
wpMngr.AddWebPart(wp, "left", 0);
}
}
private static void Main(string[] args)
{
Program p = new Program();
p.AddWebPart( new WebPart1() );
p.AddWebPart( new WebPart2() );
}
}
}