首页 > 解决方案 > 如何从字符串中获取文件夹(在我的项目中)?(C#)

问题描述

我的意思是,如果我的项目中有这样的树:

MyProject > MyPrograms > Program1 > DoSomething.cs
                       > Program2 > DoSomething.cs

我想在我的主程序.cs中执行这样的事情:

static void Main(string[] args) {
    DoStuff("Program1"); // Program1 being a folder
}

static void DoStuff(string program) {
    new MyProject.MyPrograms.program\* This being the string *\.DoSomething(); // This is the line
}

如何使用字符串访问程序的 DoSomething?(假设所有程序都有相同的文件)

(PS:我不是说复制到输出目录,我真的是指在应用程序运行时)

例子:

项目树示例

标签: c#

解决方案


如果您想根据字符串选择在运行时调用的方法或行为,请尝试查看接口和抽象类概念。根据它们的实现,它们可以执行不同的功能。

interface ISomething
{
  void DoSomething();
}

class SomethingA : ISomething
{
    public void DoSomething() 
   {
     Console.WriteLine("A");
   }
}

class SomethingB : ISomething
{
    public void DoSomething() 
   {
     Console.WriteLine("B");
   }
}

在执行中,您可以检查字符串并相应地创建SomethingA或SomethingB的对象类型并调用该方法。

 static void Main(string[] args) 
{
    ISomething obj;
    
    if(args[0] == "Program1") 
    {
     obj = new SomethingA();
    }
    else 
    {
     obj = new SomethingB();
    }        

    obj.DoSomething();        
}

如果要在 DoSomething 方法中使用基于字符串的名称创建文件夹,请查看如何创建文件夹


推荐阅读