多态性ASP.NET C# [英] Polymorphism ASP.NET C#
问题描述
嗨
我一直在读关于OOP的文章,然后我遇到了Polymorphism,它消除了if条件。
我想要尝试在我的登录页面上实现多态性。
2位用户
1.管理员
2 .Oridnary用户
如果用户的角色是ADMIN,它应该重定向到管理页面
如何我可以在不使用if else条件的情况下完成这种情况吗?
希望有人用多态性启发我:)
抱歉我的英语不好用英语:(
编辑
忘记登录条件
Hi
I've been reading article about OOPs, and then I came across with Polymorphism which eliminate the if condition.
I would like to give it a try to implemente Polymorphism on my Login page.
2 users
1. ADMIN
2. Oridnary Users
If the role of the user is ADMIN it should redirect to Admin Page
How can I accomplish this kind of scenario without using if else condition ?
Hope someone Enlighten me with Polymorphism :)
Sorry for my bad English not too good with english :(
EDIT
Forgot my Login Condition
If Login.isAuthorized() Then 'Says that Account is Registered
If Login.isAdminUser Then 'Redirect to Admin.aspx if Account role is Admin
Response.Redirect("~/Admin.aspx", False)
Else
If Login.isOrdinaryUser Then
Response.Redirect("~/OrdinaryUser.aspx", False)
Else
lblError.Text = "Access Denied!"
End If
End If
Else
lblError.Text = "Access Denied!"
End If
推荐答案
多态性没有在角色上工作:它适用于课程。
因此,如果你有一个User类和Admin类,那么你可以创建一个展示多态性的GoHome方法:
Polymorphism doesn't work on roles: it works on classes.
So if you have a User class, and Admin class, then you can create a "GoHome" method that exhibitys polymorphism:
public void GoHome(User u) { GoPage("userhome.aspx?u=" + u.Name); }
public void GoHome(Admin a) { GoPage("adminhome.aspx?u=" + a.Name); }
但是你不能根据变量的值使用多态:
But you cannot use polymorphism based on the value of a variable:
public void GoHome(userType==User) { GoPage("userhome.aspx?u=" + u.Name); }
public void GoHome(userType==Admin) { GoPage("adminhome.aspx?u=" + a.Name); }
它不会编译或工作。
多态性不适用于角色:它适用于类。
Polymorphism doesn't work on roles: it works on classes.
绝对有礼,但我们可以使用丢失耦合或接口来做同样的事情
Absolutely rite but we can do the same using lose coupling or interface
public interface IUser
{
string GoHome();
}
public enum Level
{
Lvl_1,
Lvl_2,
Lvl_3
}
public class Admin: IUser
{
public Level Level { get;set;}
public string GoHome()
{
string URL=string.Empty;
switch(Level)
{
case Lvl_1:
URL="Your Preferd URL";
break;
...
}
return URL;
}
}
// Calling
void RedirectToHome(IUser User)
{
Response.Redirect(User.GoHome());
}
这篇关于多态性ASP.NET C#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!