我正在 Unity 上用 C# 開發一個游戲,旨在學習 Python 的基礎知識。
在我的專案中,我創建了一個抽象類Execution,它定義了 Python 中不同型別的執行:
public abstract class Execution
{
public enum ExecutionType
{
Affectation,
Incrementation,
Decrementation,
Multiplier,
Divisor,
EntireDivisor,
Modulo,
IfStatement,
ElseStatement,
ForLoop,
WhileLoop,
Pass,
}
public ExecutionType Type;
public abstract string Representation();
public Execution(ExecutionType type)
{
type = Type;
}
// Some others methods
}
這是從Execution派生的類的示例:
public class Pass : Execution
{
public Pass() : base(ExecutionType.Pass) { }
public override string Representation()
{
return IndentRepresentation($"<color=#eb8f34>pass</color>");
}
}
所有這些都允許我在另一個腳本中創建一個隨機的 Python 代碼生成器,所以我開始考慮一種演算法,該演算法允許生成一個 Python 代碼,該代碼通過為每一行實體化一個從Execution類派生的類來作業。
int randomIndex = 0; // Generated in the algorithm
List<Type> ExecutionsTypes = new List<Type>();
ExecutionsTypes.Add(typeof(Affectation)); // Error
ExecutionsTypes.Add(typeof(Pass));
Execution execution = (Execution)Activator.CreateInstance(ExecutionsTypes[randomIndex]); // Sometimes errors
我的問題是我想將這些類的所有型別存盤在一個串列中,并能夠通過瀏覽串列來實體化它們,但是,有些類是通用類(所以我在這些地方有錯誤),但其他類有必要的引數,而且由于選擇是隨機的,我不知道如何放置必要的引數。
uj5u.com熱心網友回復:
為了使用Activator.CreateInstance(someType)每個型別必須有一個無引數的建構式。您指出有時您會收到錯誤訊息,因此很明顯您的某些類沒有。即使他們這樣做了,這也是一個困難的設計,因為稍后您可能想要添加一個沒有默認建構式的型別,而您將無法添加。
一種方法是創建實體化類串列而不是型別串列。
取而代之的是:
List<Type> executionsTypes = new List<Type>();
executionsTypes.Add(typeof(Affectation));
executionsTypes.Add(typeof(Pass));
做這個:
List<Execution> executions = new List<Execution>();
executions.Add(new Affectation());
executions.Add(new Pass());
然后,您可以選擇一個已經實體化的類實體,而不是從串列中選擇一個型別并實體化它。
如果您不想重用類實體并且每次都需要一個新實體怎么辦?那么你可以這樣做:
List<Func<Execution>> executions = new List<Func<Execution>>();
executions.Add(() => new Affectation());
executions.Add(() => new Pass());
executions.Add(() => new SomeTypeWithParameters("x", 1));
然后,您從串列中選擇的是一個回傳 的函式,Execution您可以呼叫它來創建一個新實體。
Func<Execution> createExecutionFunction = // however you randomly select one
Execution execution = createExecutionFunction();
轉載請註明出處,本文鏈接:https://www.uj5u.com/ruanti/396282.html
上一篇:列出每行帶有-v符號的檔案名
