c# - 如何从字符串中获取文件夹(在我的项目中)?(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:我不是说复制到输出目录,我真的是指在应用程序运行时)
例子:
解决方案
如果您想根据字符串选择在运行时调用的方法或行为,请尝试查看接口和抽象类概念。根据它们的实现,它们可以执行不同的功能。
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 方法中使用基于字符串的名称创建文件夹,请查看如何创建文件夹
推荐阅读
- javascript - How to listen to the input event of the Stripe cardElement to determine if card is invalid and disable the button?
- html - 在 flexbox 中将图像居中
- python - 在python上保存变量的输入
- delphi - Retry after exception in delphi
- api - 如何制作侮辱命令(discord.py)
- html - 如何将 CSS 动画添加到 ReactJs 组件
- python - 使用字典将数据帧子集到多个
- javascript - Object transformation assistance
- node.js - TypeError: brain.NeuralNetwork is not a constructor
- mysql - 如何使用正则表达式在 SQL 中根据其他列添加新列