Erstellen Sie eine Variable, die eine Aktion enthält [Duplikat]
Ich versuche eine Variable zu erstellen, die beim Aufrufen einen Code ausführt.
Zum Beispiel
string path1;
string path2;
bool check;
var make;// the variable in case
//other code
if(check == false)
{
make = File.Copy(path1, path2); // the thing impossible to do
}
else
{
make = File.Move(path1, path2);
}
make;//and here it should to run some code
Dadurch wird der in make enthaltene Code nicht ausgeführt .
Der Code darf jedoch keinen internen Compiler wie Roslyn verwenden, da er zu langsam ist.
Ich habe es so versucht, aber es funktioniert nicht:
Action make = File.Copy(path1, path2);
Ich nicht möchte eine Funktion verwenden:
public void main()
{
make();
}
public void make()
{
if(check == false)
{
make = File.Copy(path1, path2);
}
else
{
make = File.Move(path1, path2);
}
}
Ist das möglich? Danken
Antworten
Ich denke, Sie müssen die Macht der Delegierten nutzen. Ihr Ziel kann einfach mit diesem Code erreicht werden:
string path1;
string path2;
bool check;
Action make = null;// the variable in case
//other code
if(check == false)
{
make = () => File.Copy(path1, path2); // the thing impossible to do
}
else
{
make = () => File.Move(path1, path2);
}
make();//and here it should to run some code
Du warst so super nah. Es ging nur darum, die Syntax richtig zu machen.
Hier ist es:
Action make;
if (check == false)
{
make = () => File.Copy(path1, path2);
}
else
{
make = () => File.Move(path1, path2);
}
make();
Action(im Gegensatz zu Action<T>oder Action<T1, T2>zum Beispiel) nimmt keine Parameter an, daher müssen Sie dies mit den leeren Parametern unter angeben () =>.