【发布时间】:2018-09-01 12:44:33
【问题描述】:
目前我正在尝试以编程方式,File.ReadAllText 一个 C# (.cs) 文件并将其转换为 Type 对象,以便我可以访问 Type.GetMethods() 函数(以及其余函数)。这个 .cs 文件不在同一个项目中,这就是为什么我不能只在代码本身中调用该类。
唯一的问题是我找不到这样做的方法。我通过使用 TypeDescriptor 将字符串转换为类型对象尝试了以下操作,但失败并出现错误。
代码:
string code = File.ReadAllText(PathToHomeControllerFile);
Type t = (Type)TypeDescriptor.GetConverter(typeof(String)).ConvertTo(code, typeof(Type));
string methods = string.Join(",", t.GetMethods().Select(p => p.Name));
Console.WriteLine(methods);
我正在尝试转换的文件 (HomeController.cs):
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
namespace TestApplication.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult TestAction()
{
return View();
}
}
}
错误:
'StringConverter' 无法将 'System.String' 转换为 'System.Type'。
我如何实现我的目标?
【问题讨论】:
-
好吧,您需要编译代码 - 这绝非易事,因为您需要知道要引用哪些其他程序集等。
-
@JonSkeet 是否可以以编程方式编译代码?如果是这样,怎么做? :)
-
有可能,但不要指望它是单行的。网上有 很多 资源与此相关 - 我建议您搜索 Roslyn 的教程。
-
@JonSkeet 嗯.. 真的没有其他办法了吗?我基本上只想要关于函数的信息(名称、返回类型和输入参数,仅此而已)
-
@RB。好吧,用例在 VSIX 扩展中,我需要在其中获取有关所有 MVC 控制器的信息,因此每次单击 VSIX 扩展的自定义按钮时,我都可以创建有关这些信息的报告,因此将其构建到 DLL 中有点过的问题。
标签: c# .net model-view-controller types type-conversion