【发布时间】:2011-05-12 02:56:26
【问题描述】:
过去几天我一直在学习 C#,以便与 ASP.NET 一起使用来创建网站。
我对 C# 很陌生,但我一直在思考应该如何编写代码以使其尽可能可重用。
举个简单的例子,假设我想创建一段代码来检查用户的登录详细信息,我可以随时将其放入另一个站点,并让它与提供的数据一起工作。
记住我不知道我应该如何布局我的代码来做到这一点,这就是我想出的想法(我会用某种伪代码保持简短):
首先我创建一个类:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
namespace Module {
public class Login {
public static bool check_login(string usernameCheck = "", string passwordCheck = "") {
if(usernameCheck == "user" && passwordCheck == "password") {
return true;
}
return false;
}
}
}
然后我会有一个登录表单所在的 aspx 页面,例如:
<asp:Content ContentPlaceHolderID="column1" runat="server">
<asp:TextBox ID="usernameInput" runat="server"></asp:TextBox>
<asp:TextBox ID="passwordInput" runat="server"></asp:TextBox>
<asp:Button OnClick="check_login" Text="Login" runat="server" />
</asp:Content>
文件后面的代码如下所示:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
namespace Module {
public partial class _default : System.Web.UI.Page {
protected void Page_Load(object sender, EventArgs e) {
}
protected void check_login(object sender, EventArgs e) {
if(Login.check_login(usernameInput.Text, passwordInput.Text)) {
Response.Redirect("some other place");
}
}
}
}
这按预期工作,但我想知道的是:
- 有没有更好的方法来创建可重用的代码?
- 如何设计可重用代码?
我确信一定有更好的方法可以做到这一点,但我自己想不出。
【问题讨论】:
标签: c# .net reusability