C# 如何在方法中传递泛型类以使此代码可重用
每次我需要传递一个新的页面类时,我都会调用这个类。我必须构建一个新的构造函数,我知道泛型可以解决这个问题。有人能告诉我怎么做吗C# 如何在方法中传递泛型类以使此代码可重用,c#,generics,C#,Generics,每次我需要传递一个新的页面类时,我都会调用这个类。我必须构建一个新的构造函数,我知道泛型可以解决这个问题。有人能告诉我怎么做吗 public class CheckUserAuthentication { private Page1 _p1; private Page2 _p2; public CheckUserAuthentication(Page1 p1) { _p1 = p1;
public class CheckUserAuthentication
{
private Page1 _p1;
private Page2 _p2;
public CheckUserAuthentication(Page1 p1)
{
_p1 = p1;
}
public CheckUserAuthentication(Page2 p2)
{
_p2 = p2;
}
public void AuthenticateUser(out Person person, out Animal animal)
{
If(_p1 != null)
{
_p1.Response.Write("writes to P1 page");
}
else
{
_p2.Response.Write("writes to P2 page");
}
}
}
我第一页的呼叫代码
public Page1()
{
_checkUserAuthentication = new CheckUserAuthentication(this);
}
public CheckUserAuthentication CheckUserAuthentication
{
get { return _checkUserAuthentication; }
}
CheckUserAuthentication.AuthenticateUser(out person, out animal);
您最好使用一个界面:
public interface IPage {
public HttpResponse Response { get; set; }
}
public class Page1 : IPage {
}
public class Page2 : IPage {
}
public class CheckuserAuthentication {
private IPage _page;
public CheckuserAuthentication(IPage page) {
_page = page;
}
public void AuthenticateUser(out Person person, out Animal animal) {
_page.Response.Write("Doesn't matter what page it writes to.. it will write to whatever you pass in..");
}
}
如果没有更完整的
CheckuserAuthentication
实现,就很难为您提供帮助。您有实例和静态方法。。我们需要看到这两种类型,才能给你们一个清晰的例子。我现在再补充一些。