简体   繁体   English

ASP.NET MVC如何将页面名称与类名称相关联?

[英]How does ASP.NET MVC associate page names with class names?

I'm new to ASP.NET MVC and I'm confused about how in a compiled language like C#, class names can have any meaning after the project has been built. 我是ASP.NET MVC的新手,我对在C#这样的编译语言中如何在创建项目后使用类名具有任何含义感到困惑。 Can someone explain to me how the building process takes 有人可以向我解释建造过程如何进行

public class SomePageController : Controller {
     public ActionResult Index() { return View(); }
}

and grabs the names SomePage and Index to create a URL map SomePage/Index that calls the function Index() ? 并获取名称SomePageIndex来创建调用函数Index()的URL映射SomePage/Index I only understand how this works if there is some other C# file that somehow able to look at all classes derived from the Controller class and get a string that is their name without the suffix "Controller" . 我只了解如果还有其他C#文件能够以某种方式查看从Controller类派生的所有类并获得其名称不带后缀"Controller"的字符串,则该方法如何工作。 But that seems weird to me coming from a C++ background because I've never seen a way that a language can have of variables referencing their own name, nor have I ever seen a way to iterate through all classes derived from a certain class. 但是对于来自C ++背景的人来说,这似乎很奇怪,因为我从未见过一种语言可以具有引用其自身名称的变量的方法,也从未见过遍历从某个类派生的所有类的方法。

Maybe someone can show me how to write a C# procedure like 也许有人可以向我展示如何编写C#过程,例如

public class SomePageController : Controller {
     public ActionResult Index() { return View(); }
}

public class SomeOtherPageController : Controller {
     public ActionResult Index() { return View(); }
}

public void printPageNames ( void )
{
    // ... Will print "SomePage, SomeOtherPage" to the console
}

What you need to read into is Reflection . 您需要阅读的是反射 It allows you to look at all of the classes, properties, etc within an assembly. 它允许您查看程序集中的所有类,属性等。

To directly answer your question, Jon Skeet has the starting point of how to accomplish this. 为了直接回答您的问题, Jon Skeet具有实现此目标的起点

Your code would look something like this: 您的代码如下所示:

var assembly = Assembly.GetExecutingAssembly();

foreach (var controller in assembly.GetTypes().Where(a => a.Name.EndsWith("Controller"))
{
    Console.WriteLine(controller.Name.TrimEnd("Controller"));
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM