如何在我的方法中传递泛型类,以便此代码可重用

时间:2013-04-07 00:05:50

标签: c# generics

我每次调用我需要传递一个新的页面类我必须构建一个新的构造函数,我知道泛型会解决这个问题。有人能告诉我这是怎么做到的吗?

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

我的第1页调用代码

public Page1()
{
    _checkUserAuthentication = new CheckUserAuthentication(this);
}

public CheckUserAuthentication CheckUserAuthentication
{
    get { return _checkUserAuthentication; }
}

CheckUserAuthentication.AuthenticateUser(out person, out animal);

1 个答案:

答案 0 :(得分:0)

最好使用界面:

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