Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
89 views
in Technique[技术] by (71.8m points)

How can I get a folder (in my project) from string? (C#)

What I mean is, if I were to have something like this tree in my project:

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

And I wanted to execute something like this in my main program.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
}

How would I access the program's DoSomething by using a string? (Asuming all the programs have the same file)

(PS: I do not mean Copy to Output Directory, I really mean at runtime in the application)

Example:

example of project tree

question from:https://stackoverflow.com/questions/65648756/how-can-i-get-a-folder-in-my-project-from-string-c

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

If you want to choose what method or behavior you call at runtime based on a string, then try looking at interface and abstract class concepts. Based on their implementation, they can perform different functions.

interface ISomething
{
  void DoSomething();
}

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

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

In the execution, you can check for the string and create a type of the object accordingly of SomethingA or SomethingB and call the method.

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

    obj.DoSomething();        
}

If you want to create a folder in DoSomething method with a name based on the string, look at How to create a folder


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...