简体   繁体   中英

Converting .cs file to Type object in c#

Currently I'm trying to programmatically, File.ReadAllText a C# (.cs) file and convert it to a Type object so I can access the Type.GetMethods() function (and the rest of the functions). This .cs file is NOT in the same project, which is why I cannot just call the class in the code itself.

Only issue is I cannot find the way to do this. I've tried the following below by converting a String to a Type Object with the TypeDescriptor, but it failed with an error.

Code:

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

File I'm trying to convert (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();
        }
    }
}

Error:

'StringConverter' is unable to convert 'System.String' to 'System.Type'.

How do I achieve my goal?

Since I was working with VSIX Extensions, I could simply go with CodeModel.CodeElements as stated in the comments on the original post. I found an answer by another fellow Stackoverflower and that did the trick.

Visual Studio Extension get all classes and interfaces metadata

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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