[英]Instantiate a inherited class using a static method from a base class
我有一個抽象基類,我繼承了許多繼承的類。 我想做的是一個靜態成員接收一個字符串,它是第一個可以解析該字符串的類(只有一個繼承的類應該能夠解析)並返回該繼承類的實例。
這就是我目前正在做的。
public static Epl2Command GenerateCommandFromText(string command)
{
lock (GenerateCommandFromTextSyncRoot)
{
if (!Init)
{
Assembly a = Assembly.GetAssembly(typeof(Epl2Command));
Types = new List<Type>(a.GetTypes());
Types = Types.FindAll(b => b.IsSubclassOf(typeof(Epl2Command)));
Init = true;
}
}
Epl2Command ret = null;
foreach (Type t in Types)
{
MethodInfo method = t.GetMethod("GenerateCommand", BindingFlags.Static | BindingFlags.Public);
if (method != null)
ret = (Epl2Command)method.Invoke(null, new object[] { command });
if (ret != null)
break;
}
return ret;
}
我希望這樣做,這樣我的代碼就可以檢查所有繼承的類,而無需將來的程序員在添加更多繼承的類時返回並編輯此函數。
有沒有辦法強制繼承的類實現自己的GenerateCommand(string)
?
public static abstract Epl2Command GenerateCommand(string command)
無效c#。 或者我應該用錘子在用鞋釘釘子 ; 任何更好的方式來做此類工廠將不勝感激。
C#不支持靜態接口,因此您無法定義靜態生成器方法,例如
public interface ICommand
{
static ICommand CreateCommand(string command);
}
我同意Kevin的觀點,即您需要使用Factory模式。 我將更進一步,說您也需要針對每種命令類型構建一個構建器。 像這樣
public interface ICommandBuilder
{
bool CanParse(string input);
ICommand Build(string input);
}
public interface ICommandBuilder<TCommand> : ICommandBuilder
where TCommand : ICommand
{
TCommand Build(string input);
}
然后,您的工廠可以接受任何輸入命令字符串,查詢所有構建器是否可以解析該字符串,然后在一個可以運行的構建器上運行Build。
public interface ICommandFactory
{
ICommand Build(string input);
}
public class CommandFactory
{
public ICommand Build(string input)
{
var builder = container.ResolveAll(typeof(ICommandBuilder))
.First(x => x.CanParse(input));
return builder.Build(input);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.